Sunday, 8 September 2013

private inheritance in C++

private inheritance in C++

I am learning the concepts of OOPS, and came across private inheritance.
From what I've learnt - When a class derives from a base class and letter
when the derived class is instantiated, the constructor of the Base class
is called first, followed by the constructor of the derived class. So, in
the code "A created" would be printed first. The problem is since the
inheritance is private, all the members of A would be private inside B, so
how can the constructor of A be called when B is instantiated. Going by
this logic, the following code should generate errors, but when I run it,
it compiles fine, and gives the output "A created" followed by "B
created". How is this happening? Or am I making some mistake in
understanding the concept?
#include <iostream>
using namespace std;
class A{
public:
A(void)
{
cout<<"A created"<<endl;
}
~A()
{
//do nothing
}
void doSomething(void)
{
cout<<"hi";
}
};
class B:private A
{
public:
B(void)
{
cout<<"B created"<<endl;
}
~B()
{
//do nothing
}
};
int main() {
B* myptr = new B();
//myptr->doSomething();
delete myptr;
return 0;
}

No comments:

Post a Comment