6

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
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084

1 Answers1

7

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
};
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • can you explain how my given example works? I mean can you show me code of background processing in my given example? –  Jul 11 '15 at 13:17
  • @LetDoit: I don't quite understand your question. Your definition of `B::B()` implies the default construction of the `A` subobject; it's like you if you had written `B::B() : A() { /* your code */ }`. – Kerrek SB Jul 11 '15 at 13:43
  • in my example `B( )` implicitly calls the default constructor of A's class? Such as. `B() : A() { }` –  Jul 11 '15 at 15:32
  • 1
    @LetDoit: Isn't that what I just said? – Kerrek SB Jul 11 '15 at 16:10