A member function with the same name as its class is called a constructor. It is used to initialize the objects of that class-type with a some initial value. If a class has a constructor, each of the objects of that class will be initialized before they are used within the program.

A constructor for a class is needed, so that the compiler automatically initializes an object as soon as it is created. A class constructor is defined without any return-type. They are called whenever a program creates an object of that class.

Declaration and definition

A constructor is defined like any other member function of a class except that it does not have any return-type associated with it. It can be defined either inside the class definition or outside the class definition.

Syntax:

A constructor can be defined in any of the private, protected or public section.

Default Constructors

A constructor that does not accept any parameters is called default constructor. In the previous example salesperson::salesperson() is the default constructor for class salesperson, since it does not take any parameters.

Note: If a class has no explicit constructor defined, the compiler will supply a default constructor, having no arguments.

A default constructor supplied by the compiler does not do any thing special; it just initializes the data members with dummy values.

Output:

Copy Constructor

A copy constructor is a constructor of the form classname(classname &). The compiler will use the copy constructor whenever you initialize an instance, using values of another instance of the same type.

Example:

The second statement will copy the instance of S1 to S2.

Destructors

Whenever an object is created within a program, it also needs to be destroyed. If a class has constructor to initialize members, it should also have a destructor to free up the used memory. A destructor, as the name suggest, destroys the values of the object created by the constructor when the object goes out of scope.

A destructor is also a member function whose name is the same name as that of a class, but is preceded by tilde (‘~`).

For example, the destructor of class salesperson will be ~salesperson(). A destructor does not take any arguments nor does it return any value. The compiler automatically calls them when the objects are destroyed.

Need for a Destructor

During the construction of the object by the constructor, some resources may be allocated for use. For example, some memory space may be allocated to the data members. These resources must be de-allocated and the memory space should be freed before the object is destroyed.