-3

Here is the Answer.

A()
B(int)
C(int)
~C()
~B()
~A()

But I don`t know why I get this output.

class A {
public:
    A() { cout << "A()\n"; }
    ~A() { cout << "~A()\n"; }
};

class B : public A {
public:
    B() { cout << "B()\n"; }
    B(int i) { cout << "B(int)\n"; }
    ~B() { cout << "~B()\n"; }
};

class C : public B {
public:
    C() { cout << "C()\n"; }
    C(int i) : B(i) { cout << "C(int)\n"; }
    ~C() { cout << "~C()\n"; } 
};

void main() {
    C *b = new C(3);
    delete b;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770

1 Answers1

1

C(int) explicitly calls B(int) in its member initialization list before then logging itself in its body.

B(int) implicitly calls A() before then logging itself in its body.

Base classes are constructed before derived classes. This is why you see the constructors logged as A(), then B(int), then C(int).

~C() implicitly calls ~B() at the end after logging itself.

~B() implicitly calls ~A() at the end after logging itself.

Base classes are destructed after derived classes. This is why you see the destructors logged as ~C(), then ~B(), then ~A().

Any decent C++ book or tutorial should cover how constructors and destructors are called in relation to each other in a parent/child hierarchy.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770