Skip to main content
gamedev.net
🔒 Locked

Inheritance

Started by alberto_balsalm 2 replies 300+ views
Original Post
alberto_balsalm
alberto_balsalm
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
Oluseyi
Oluseyi
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
{
...
};
Fruny
Fruny
Ahhh, multiple inheritance...

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

D will only get a single copy of A.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.