Wednesday, February 25, 2009

Constructor & Destructor

Constructor :- 
Constructor creates an object and initializes it. It also creates V-Table for virtual functions. It is different from other methods in a class.
Constructors are used to create, and can initialize, objects of their class type. 
You cannot declare a constructor as virtual or static, nor can you declare a constructor as const, volatile, or const volatile. 
You do not specify a return type for a constructor. A return statement in the body of a constructor cannot have a return value.

Virtual Constructor :-
It is not possible to have Virtual Constructor.The constructor can’t be virtual as the constructor is a code which is responsible for creating an instance of a class and it can’t be delegated to any other object by virtual keyword means.

Destructor :- 
Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed. A destructor is called for a class object when that object passes out of scope or is explicitly deleted.

Virtual Destructor :- 
A Virtual destructor can be virtual as it is possible as at runtime depending on the type of object caller is calling to, proper destructor will be called.

pseudo-destructor :-
A pseudo-destructor is a destructor of a nonclass type.
The following example calls the pseudo destructor for an integer type:
typedef int I;
int main() {
I x = 10;
x.I::~I();
x = 20;
}

The call to the pseudo destructor, x.I::~I(), has no effect at all. Object x has not been destroyed; the assignment x = 20 is still valid. Because pseudo destructors require the syntax for explicitly calling a destructor for a nonclass type to be valid, you can write code without having to know whether or not a destructor exists for a given type.

No comments:

Post a Comment