#include <iostream>
using namespace std;
class base{
public:
int i;
base(){
i=1;
cout<<"Base Constructor";
}
};
class derived: private base{
public:
derived(){
i=2;
cout<<"Derived constructor";
}
};
int main(){
derived c;
return 0;
}
For the above code why am I getting the output as
"Base ConstructorDerived Constructor"
even though I inherited using private?
Why am I still be able to access it from main function?
You aren't.
Your main function accesses derived
's constructor, which it has access to.
And derived
's constructor accesses base
's constructor, which it has access to.
A constructor automatically initializes the base classes and the members before executing the body of the constructor. Private inheritance doesn't change that. It just makes the base part of the class not accessible outside the class. Since it is the derived class constructor that is calling the base class constructor, the private inheritance doesn't restrict what it can do.
What you mean to do is make the constructor of the base class protected
. Then only derived classes can use it:
class base
{
protected:
base() : i(1) { }
private:
int i;
};
class derived : private base
{
public:
derived() : base() { }
};
int main()
{
// base b; // error: inaccessible constructor base::base()
derived d; // fine
}
A somewhat popular pattern is also to make the destructor protected. You get the point, though.