In: Computer Science
What does this program output
(make sure you can explain why the output is what it
is)
#include <iostream>
using namespace std;
class A {
int i;
public:
A() {cout << "A()\n" ;}
A(int x) :i(x) {cout << "A(int)\n" ;}
A(const A& a) : i(a.i) {cout << "A(const
A&)\n" ;}
~A() {cout << "A()\n" ;}
};
class B {
A a;
public:
B() {cout << "B()\n" ;}
B(int x) :a(x) {cout << "B(int)\n" ;}
B(const B& b) : a(b.a) {cout << "B(const
B&)\n" ;}
~B() {cout << "~B()\n" ;}
};
B func(B k) {return k;}
int main() {
B b1(2), b2;
b2=func(b1);
return 0;
}
The basic rule is constructors are always called in this order -
base classes to derived
destructors are always called in reverse order - i.e derived class
destructors first upto to base class destructors.
In this example since B derives from A, when ever an object of B
is created, the corresponding constructor in A is called first.
Then B's constructor.
Whenever an object of B goes out of scope/destroyed, B's destructor
is called first and then A's destructor.
The output of the program is
A(int)
B(int)
A()
B()
A(const A&)
B(const B&)
A(const A&)
B(const B&)
~B()
A()
~B()
A()
~B()
A()
~B()
A()
- In main(), object b1 is created . this leads to 2 constructor
calls A(int) and B(int)
- next object b2 is created, this leads to 2 constructor calls A()
, B()
-Now function func() is called. Since it receives parameter by
value, a copy of b1 is made using copy constructor. So this leads
to A(const A&) , B(const B&)
-Next when the function returns, the value from k is copied into an
intermediate object i.e return value of func(). This again leads
A(const A&) , B(const B&)
-After the function returns, k is destroyed. So this leads to ~B()
and ~A()
-After the return value is assigned to b2, that intermediate object
is destroyed again leading to ~B() and ~A()
-Next object b1 and b2 go out of scope/destroyed . Hence 2 sets of
~B() and ~A()