Archived

This topic is now archived and is closed to further replies.

Inheritance

This topic is 5899 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I working on a school project and i'm having a bit of problem with inheritance. Have a look at this code:
#include 
#include 

class A
{
protected:
    int z;
};

class B : public A
{};

class C : public A
{};

class D : public B, public C
{};

int main(int argc, char **argv)
{
    D d;
    cout << d.z;
    getch();
}
[/Code]

This code give me the following error message:

[C++Error] Project2.cpp(23): Member is ambiguous: 'A::z' and 'A::z'.

I want to inherit the objects like that but I don't know how to fix it. Anyone know what to do?


     
Edited by - alberto_balsalm on November 22, 2001 3:54:20 PM

Share this post


Link to post
Share on other sites
The error results because D contains two z data members, one through B and one through C (both of which inherit through A). The solution to this is to use virtual inheritance:

class A
{
...
};
class B : public A
{
...
};
class C : public A
{
...
};
class D : virtual public B, virtual public C
{
...
};

Share this post


Link to post
Share on other sites
Ahhh, multiple inheritance...

class B : virtual public A;
class C : virtual public A;

D will only get a single copy of A.

Share this post


Link to post
Share on other sites