Currently, I am learning OOP, and I've tried many inheritance examples. I just tested this code:
#include <iostream>
using namespace std;
class B
{
int a;
protected:
B(int i=0)
{
a=i;
}
int get_b()
{
return a;
}
};
class D: private B
{
public:
D(int x=0): B(x) {}
int get_a()
{
return get_b();
}
};
int main()
{
D d(-89);
cout << d.get_a();
return 0;
}
Why does this work? Why can I use the get_b()
function? Why does the constructor B(x)
work? Why doesn't it work if I change protected
to private
then?
Later Edit : By using the protected
keyword on the constructor and function get_b()
means that derived classes have acces to them if the inheritance is public. However, in this case by using private inheritance I would expect that the constructor and the get_b()
function would be inaccesible from class D
.