Refer to base class members from a derived class

class A { public: void fa() { } }; class B : public A{ public: void fb() { } }; class C : public A, public B { public: void fc() { //call A::fa(), not B::A::fa(); } }; 

How to call the function A::fa() from C::fc() .

GCC warns with direct base A inaccessible in C due to ambiguity , does this mean that there is no direct way to reference base classes?

+7
source share
5 answers

One option is to create a stub class that you can use for casting in a subobject of the right base class:

 struct A { void fa() { } }; struct B : A { void fb() { } }; // Use a stub class that we can cast through: struct A_ : A { }; struct C : A_, B { void fc() { implicit_cast<A_&>(*this).fa(); } }; 

Where implicit_cast is defined as:

 template <typename T> struct identity { typedef T type; } template <typename T> T implicit_cast(typename identity<T>::type& x) { return x; } 
+8
source

I just found the following information from the ISO C ++ 2003 standard (10.1.3)

 A class shall not be specified as a direct base class of a derived class more than once. [Note: a class can be an indirect base class more than once and can be a direct and an indirect base class. There are limited things that can be done with such a class. The non-static data members and member functions of the direct base class cannot be referred to in the scope of the derived class. However, the static members, enumerations and types can be unambiguously referred to. 

This means that there is no direct way: (

+5
source

I just compiled code on codepad.org by adding A::fa() to call the fa () function from your C::fc() function.

  void fc() { A::fa(); } 

Below is a link to the code with your code.

http://codepad.org/NMFTFRnt

+1
source

You can use virtual inheritance to overcome this problem:

 class B : virtual public A { 

Now you can use A::fa() simply in a child class C

 void fc() { fa(); } 

However, I do not see the practical need to inherit class A again in class C , when B already public , inheriting A So in your case you can make it simple:

 class C : public B { 

Edit

If you want 2 instances for A then the direct instance that you intend can be made as a C object:

 class C : public B { A obj; 

Because if inherited A will not be directly used, in any case. You cannot declare any pointer or reference to it inside the scope of C

0
source

I don’t think you can do what you want. There is ambiguity here: when you say A::fa() , it still does not tell the compiler which object A use. No access to class A This is what warns you.

It looks like a terribly strange design. For is-a relationships, public inheritance should be used. Are you saying that C is-a A twice? It does not make sense. And this suggests that this is either an artificial example that will never arise in practice, or you should reconsider this design.

0
source

All Articles