Diamonds and redefinitions

J

John Doe

I don't understand one thing about the diamond multiple inheritance. See
the code:

------------------------------------------------------

class A
{
public:
void f() {std::cout("A");}
};

class B : virtual public A
{
public:
void f() {std::cout("B");}
};

class C : virtual public A
{
};

class D : public B, public C
{
};


int main (.........) {
D d;
d.f();

........
}

------------------------------------------------------

This code compiles OK and the B::f() is called.


BUT if I remove the virtual from the following lines:
class B : virtual public A
class C : virtual public A


THEN it gives compile error:

d:\Data\VC++7.1_projects\Prova1\Prova1.cpp(73) : error C2385: ambiguous
access of 'f' in 'D'
could be the 'f' in base 'B::f'
or the 'f' in base 'A::f'
d:\Data\VC++7.1_projects\Prova1\Prova1.cpp(73) : error C3861: 'f':
identifier not found, even with argument-dependent lookup


WHY this different behaviour???
 
G

Guest

So, where is the problem???
With your code you have this:

A
/ \
B C
\ /
D

When you remove 'virtual', you have this:

A A
| |
B C
\ /
D

So, how A will be constructed? With B-path or with C-path??

Apropos: You must use "virtual void f()" in class A (to have correct upcasting)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,189
Latest member
CryptoTaxSoftware

Latest Threads

Top