Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refer base class members from 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 A::fa() from C::fc() function.

GCC warns withdirect base A inaccessible in C due to ambiguity, does this mean there is no direct way to refer base class members?

like image 730
MKo Avatar asked Jun 27 '11 05:06

MKo


People also ask

How do you access base class members in a derived class?

A base class's private members are never accessible directly from a derived class, but can be accessed through calls to the public and protected members of the base class.

Which of the following is used to refer the base class members in derived class?

base (C# Reference) The base keyword is used to access members of the base class from within a derived class: Call a method on the base class that has been overridden by another method.

Can a derived class reference to base class object?

No. A reference to a derived class must actually refer to an instance of the derived class (or null).

Can you access the derived classes default members in base class?

If the derived class is declared with the keyword class , the default access specifier in its base list specifiers is private . If the derived class is declared with the keyword struct , the default access specifier in its base list specifiers is public .


1 Answers

One option would be to create a stub class that you can use for casting to the right base class subobject:

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; }
like image 100
James McNellis Avatar answered Oct 03 '22 18:10

James McNellis