Constructor in C++

C++ provides a special member function called the constructor which enables an object to initialize itself when it is created.

What is Constructor ?

“A constructor is a special member function whose task is to initialize the objects of its class.” It is special because its name is the same name as the class name. The constructor is invoked whenever an object of its associated class is created. It is called constructor because it constructs the values of data members of the class.

Syntax: A constructor is declared and defined as follows:

class integer
{
int m,n;
public:
   integer( )
   {
      m=0;
      n=0;
   }
};

Characteristic of Constructor:

  1. Constructor must be declared in the public section.
  2. They are invoked automatically when the objects are created.
  3. They do not have return type, not even void.
  4. They cannot be inherited, though a derived class can call the base class constructor.
  5. Like other c++ functions, they can have default arguments.
  6. Constructors cannot be virtual.
  7. They make „implicit calls‟ to the operators new and delete when memory allocation is required.

Types of Constructor:

  1. Default Constructor
  2. Parameterized Constructor
  3. Copy Constructor
  4. Dynamic Constructor
  5. Multiple Constructor (Overloading)

Related posts