I'm trying to understand the private inheritance concept.
So far everywhere I see they write that private inheritance makes its members inaccessible from the derived class.
Doesn't this make it sort of useless? If I can't access the class inherited, what is the purpose of deriving in the first place?
Now I know private classes are actually used and helpful. I'm just having trouble in understanding how.
Your question reads as if private
members would be useless altogether. I mean you could as well ask, what is a private member good for if it cannot be accessed from outside. However, a class (usually) has more than what a subclass can use.
Consider this simple example:
struct foo {
void print();
};
struct bar : private foo {
void print_bar() {
std::cout << " blablabla \n";
print();
std::cout << " bblablabla \n";
}
};
A class inheriting from bar
wont even notice that bar
inherits from foo
. Nevertheless, it does make sense for bar
to inherit from foo
, because it uses its functionality.
Note that private inheritance is actually closer to composition rather than public inheritance, and the above could also be
struct bar {
foo f;
void print_bar() {
std::cout << " blablabla \n";
print();
std::cout << " bblablabla \n";
}
};
How do I access privately inherited class members in C++?
Outside of the class: You dont, thats what the private
is for. It's not different for private members or private methods in general, they are there for a reason, you just cannot access them from outside.