Great way to earn money!

Zone1

Thursday, March 15, 2012

Some C++ Questions Part 2

What is the order of destruction of local objects and how objects in a array gets destructed

Local objects are destructed   in reverse order of construction:
First constructed, last destructed.
In the following example, b's destructor will be executed first, then a's destructor:
void userCode()
{
Fred a;
Fred b;
...
}

if we have a array of objects,  destruction occurs in reverse order of construction: 

In the following example, the order for destructors will be a[9], a[8], ..., a[1], a[0]:

void userCode()
{
Fred a[10];
...
}



Can we overload the destructor
No.
We can have only one destructor for a class. It's always called
Classname ::~Classname().
It never takes any parameters, and it never returns anything.
You can't pass parameters to the destructor anyway, since you never explicitly call a destructor.




Can one constructor of a class call another constructor of the same class to initialize the this
object?

No.
Let's work an example.
Suppose you want your constructor Foo::Foo(char) to call another constructor of the same class, say Foo::Foo(char,int), in order that Foo::Foo(char,int) would help initialize the "this" object. Unfortunately there's no way to do this in C++.
Some people do it anyway.
Unfortunately it doesn't do what they want. 
For example, the line
Foo(x, 0); does not call Foo::Foo(char,int) on the "this" object. Instead it calls Foo::Foo(char,int) to initialize a temporary, local object (not "this"), then it immediately destructs that temporary when control flows

class Foo {
public:
Foo(char x);
Foo(char x, int y);
...
};
Foo::Foo(char x)
{
...
Foo(x, 0); // this line does NOT help initialize the this object!!
...
}
We can do this rather : 



class Foo {
public:
Foo(char x, int y=0); // this line does our work
...
};