Abhinav Gauniyal Abhinav Gauniyal - 2 months ago 14
C++ Question

error: 'A' is an inaccessible base of 'B'

I've a code as follows -

#include <iostream>
#include <string>

class A{
int a;
public: virtual void sayHello(){ std::cout << "Hello\n"; }
};

class B : private A{
std::string name;
public:
B(std::string _n): name(_n){}
void sayName(){std::cout << name << "says hello\n";}
void sayHello(){sayName();}
};


int main() {
A *ptr = new B("c++");
ptr->sayHello();
return 0;
}


which produces the following compiler output -


Error:

prog.cpp: In function 'int main()':
prog.cpp:20:22: error: 'A' is an inaccessible base of 'B'
A *ptr = new B("c++");
^



As previously answered - here, here & here, I know how to solve this issue. By using
public
inheritence instead of
private
or
protected
.

But if I really really want to hide some interface behind the base class, isn't there some other way to do this? Or is it impossible to do so according to c++ lang specification.

Answer

If you want polymorphic pointer conversion to work outside the class, then the inheritance must be public. There is no way to work around that.

You could add a member function that does the polymorphic pointer conversion within the class:

class B : private A{
    // ...
public:
    A* getA() {
        return this;
    }
};

Which allows you to do this, while still allowing private inheritance:

B* b_ptr = new B("c++");
A* ptr   = ptr->getA();
//A* ptr2 = b_ptr; // only allowed in member functions

I haven't encountered a real world design where this trick would be useful, but suit yourself.


PS. Remember that you should destroy objects that you create. Also do realize that delete ptr has undefined behaviour, unless ~A is virtual.

Comments