I have this part of code
#include <iostream>
using namespace std;
class A {
public:
int i;
A(){i = 0; }
virtual void f() { cout << i; }
};
class B1 : virtual public A {
public:
B1() { f(); }
void f() { cout << i+10; }
};
class B2 : virtual public A {
public:
B2() { f(); }
void f() { cout << i+1; }
};
class C : public B1, public B2 {
public:
C() {}
};
void main(){
C c;
//c.A::f();
}
First, I understand the main idea behind using virtual inheritance (diamond) in order to create only one A
object in memory.
In this example, I get compilation error in C
class:
override of virtual function "A::f" is ambiguous
If I remove the virtual
inheritance. The code compiles, there is no error in class C
as before.
If I remove the comment from the last code line it still compiles. I understand that in this case the f()
function that will be executed is the one from the first class that C
inherits from.
Now, if I replace c.A::f()
with c.f()
I get a compilation error at this specific line.
Can someone please explain this behaviour and the differences between these cases?