Thursday, October 16, 2008

Constructors & Destructors in C++

Constructor
Definition :
Constructor is a special member function with the same name as its class.

Example:
class Person
{

public:
Person(); // constructor for class Person
};

Use:
Constructors are used to create, and can initialize, objects of their class type.

Call:
When an object of a class is created, constructor for that class is called.

If there is no constructor defined, DEFAULT constructor is invoked.
But default constructor doesn't initialize.

Some facts about Constructors :
  • Constructors are special member functions with the same name as the class.
  • Constructors can not return any value (nothing even void) .
  • Constructors are intended to initialize the members of the class when an instance of that class is created.
  • Constructors are not called directly.
  • Constructors can not be virtual.
  • Constructors can not be static.
  • Constructors can not be const, volatile, or const volatile.
  • Constructors aren't automatically inherited between base and derived classes.
  • There can be any number of constructors in a same class. They must have different parameters to distinguish them. (=> Constructors can be overloaded )
Destructors
Definition :

Destructors in C++ also have the same name, but they are preceded by a '~' operator.

Example :
class Person {
public:
// Constructor for class Person
Person();
// Destructor for class Person
~Person();
};

Use :

Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed.

Call:

The destructors are called when the object of a class goes out of scope or is explicitly deleted.

Some facts about Destructors:
  • If the constructor/destructor is declared as private, then the class cannot be instantiated. (why? Think about it.)
  • It is not necessary to declare a constructor or a destructor inside a class. If not declared, the compiler will automatically create a default one for each.
  • A destructor takes no arguments and has no return type.
  • Its address cannot be taken.
  • Destructors cannot be declared const, volatile, const volatile or static.
  • A destructor can be declared virtual or pure virtual.

No comments: