Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a member/method of a virtual derived class

The example here doesn't make sense, but this is basically how I wrote my program in Python, and I'm now rewriting it in C++. I'm still trying to grasp multiple inheritance in C++, and what I need to do here is access A::a_print from main through the instance of C. Below you'll see what I'm talking about. Is this possible?

#include <iostream>
using namespace std;

class A {
    public:
    void a_print(const char *str) { cout << str << endl; }
};

class B: virtual A {
    public:
    void b_print() { a_print("B"); }
};

class C: virtual A, public B {
    public:
    void c_print() { a_print("C"); }
};

int main() {
    C c;
    c.a_print("A"); // Doesn't work
    c.b_print();
    c.c_print();
}

Here's the compile error.

test.cpp: In function ‘int main()’:
test.cpp:6: error: ‘void A::a_print(const char*)’ is inaccessible
test.cpp:21: error: within this context
test.cpp:21: error: ‘A’ is not an accessible base of ‘C’
like image 356
Scott Avatar asked Oct 10 '09 21:10

Scott


1 Answers

Make either B or C inherit from A using "public virtual" instead of just "virtual". Otherwise it's assumed to be privately inherited and your main() won't see A's methods.

like image 183
Grandpa Avatar answered Oct 19 '22 17:10

Grandpa