user5028722
user5028722

Reputation:

How constructor works in private inheritance

I know there are same question about this topic. But I'm still confused. Please explain how A's class constructor is executing with obj even I inherit A's class constructor privately.

#include <iostream>
using namespace std;
class A{
    public:
        A(){
            cout << "A" << endl;
        }
};
class B:private A{
    public:
        B(){
            cout << "B" << endl;
        }
};
int main(){
    B obj;

    return 0;
}

Output

A
B

Upvotes: 6

Views: 2390

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 476970

Private inheritance means that all public and protected base members become private in the derived class. So A::A() is a private in B, and thus perfectly accessible from B::B().

What B::B() can't use are private constructors of A (but you don't have any of those):

struct A
{
public:
    A();
protected:
    A(int);
private:
    A(int, int);
};

struct Derived : /* access irrelevant for the question */ A
{
    Derived() : A() {}      // OK
    Derived() : A(10) {}    // OK
    Derived() : A(1, 2) {}  // Error, inaccessible
};

Upvotes: 7

Related Questions