Constructor/Destructor ordering
The order in which constructors and desctructors were called were relevant in the bug I was solving this morning, so I figured a good review was in order. This tutorial was verifed in C++. For any given class the constructors for that class are called before the actual class constructor. The super class constructors of a class are called before the derived class. Destructors are called in exact reverse order of constructors. Examine the following example with it's output. You'll see that Base class constructors are called before the derived classe's constructor; every class member's constructor gets to go before the containing class.
class B
{
public:
B() { printf("class B constructor\n");}
~B() { printf("class B destructor\n");}
};
class C
{
public:
C() { printf("class C constructor\n");}
~C() { printf("class C destructor\n");}
};
class SuperA
{
public:
SuperA() { printf("SuperA constructor.\n"); }
~SuperA() { printf("SuperA destructor.\n"); }
private:
C c;
};
class A: SuperA
{
public:
A() { printf("class A constructor.\n"); }
~A() { printf("class A destructor.\n"); }
private:
B b;
};
int main()
{
A myA;
return 0;
}
Output:
class C constructor
SuperA constructor.
class B constructor
class A constructor.
class A destructor.
class B destructor
SuperA destructor.
class C destructor
Pascal Aschwanden
class B
{
public:
B() { printf("class B constructor\n");}
~B() { printf("class B destructor\n");}
};
class C
{
public:
C() { printf("class C constructor\n");}
~C() { printf("class C destructor\n");}
};
class SuperA
{
public:
SuperA() { printf("SuperA constructor.\n"); }
~SuperA() { printf("SuperA destructor.\n"); }
private:
C c;
};
class A: SuperA
{
public:
A() { printf("class A constructor.\n"); }
~A() { printf("class A destructor.\n"); }
private:
B b;
};
int main()
{
A myA;
return 0;
}
Output:
class C constructor
SuperA constructor.
class B constructor
class A constructor.
class A destructor.
class B destructor
SuperA destructor.
class C destructor
Pascal Aschwanden

0 Comments:
Post a Comment
<< Home