Private inheritance means that the base class is accessible only within the member functions of the derived class. In general you use private inheritance when you want to model a has-a
relationship, not a is-it
. It's not the case here, you are trying to directly call it in main()
. This will work instead:
#include <iostream>
class B
{
public:
int x{42};
void print()
{
std::cout << x;
}
};
class D: private B
{
public:
void f()
{
print(); // can access the private one in B
}
};
int main()
{
D d;
d.f();
}
Live on Coliru
You can read about it more here: Difference between private, public, and protected inheritance
Or, as @WhozCraig mentioned, you can change the access via a using
statement in the public
section of your derived class:
using B::print; // now it is visible in the derived class