I Inherited a constructor using private, Why am I

2019-06-05 21:22发布

问题:

#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?

回答1:

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.



回答2:

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.



回答3:

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.



标签: c++ oop object