PDA

View Full Version : Ambiguity/private inheritance scope [C++]


sealfin
2006.12.29, 09:09 AM
Greetings, I currently have some code in which almost every class needs to privately inherit a global parent class, and I've hit a problem when class A inherits the global parent, class B likewise inherits that global parent, and class B inherits class A; perhaps code will make more sense...

class GlobalParent
{
public:
void Say( void ) { printf( "sealfin" ); return; };
};

class Parent : private GlobalParent
{
};

class Child : private GlobalParent, private Parent
{
};

warning: direct base `GlobalParent' inaccessible in `Child' due to ambiguity

I thought that this wouldn't pose a problem, as the GlobalParent inherited by Parent should be hidden from/inaccessible to Child; except that I've obviously misunderstood the scope rules in C++, and Child is seeing both the GlobalParent it inherits, and the GlobalParent inherited by Parent, which should be hidden/private...

Any suggestions as to how to fix this?

DoG
2006.12.29, 11:08 AM
You need to use virtual inheritance, eg "class Child : public virtual Parent"

But, looking at your example code, it seems like you'd be better of rethinking the class hierarchy.

sealfin
2006.12.29, 01:08 PM
You need to use virtual inheritance

Thanks for the suggestion DoG! :D I need a better book on C++ :\ That does still seem like a bug in the inheritance scope rules though, given that the inheritance was private :\

But [...] it seems like you'd be better of rethinking the class hierarchy
Unfortunately, that isn't possible :\

DoG
2006.12.29, 01:40 PM
Thanks for the suggestion DoG! :D I need a better book on C++ :\ That does still seem like a bug in the inheritance scope rules though, given that the inheritance was private :\

Unfortunately, that isn't possible :\

When you inherit from a class as private, that doesn't mean its inaccessible. It just affects the scopes of the parent class in the inherited class, eg Parent::public becomes a part of Child::private.

Also, why is it not possible to refactor this? Your inheritance scheme seems pretty nonsensical.

OneSadCookie
2006.12.29, 05:27 PM
I've never used anything other than public inheritance... chances are you're doing something wacky :P