-
Array initializing
hi all,
Code:
#include <iostream>
using namespace std;
class A
{
public:
int i;
A(int i):i(i)
{
cout<<"A created "<<i<<endl;
}
~A()
{
cout<<" A Destroyed "<<i<<endl;
}
A()
{
cout<<"A() called"<<endl;
}
};
class B:public A
{
public:
B(int j):A(j)
{
cout<<"B created "<<i<<endl;
}
B(){ cout <<" B() called"<<endl;}
~B()
{
cout<<" B distroyed "<<i<<endl;
}
};
int main()
{
A a(100);
B b(200);
A j[] = {A(1),B(2)};
return 0;
}
the output of this would be
A created 100
A created 200
B created 200
A created 1
A created 2
B created 2
B distroyed 2
A Destroyed 2
A Destroyed 2
A Destroyed 1
B distroyed 200
A Destroyed 200
A Destroyed 100
can anyone tell me , how the distructor of B is called, after the initializationg ( A(int) is called, and then when creating B, A(int) is first called, and then B(int), which I understood, what I can't understand is why ~B() is called right after this)
Thank you in advance
-
Destructors are called first on the last things created. Look at the order of your destructors. It's the exact opposite of your constructor order.
The program's memory is a stack. First In, Last Out.
-
Code:
> A j[] = {A(1),B(2)};
This is the same as
Code:
A j[] = {A(1),A(B(2))};
Note that an object of B is created to initialize an object of A and then promptly thrown away. If you printed something from A's copy constructor you would get the following for the A(B(2)) -part:
...
A created 2
B created 2
A copy created 2
B distroyed 2
A Destroyed 2
A Destroyed 2
...