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:
Characteristic of Constructor:
- Constructor must be declared in the public section.
- They are invoked automatically when the objects are created.
- They do not have return type, not even void.
- They cannot be inherited, though a derived class can call the base class constructor.
- Like other c++ functions, they can have default arguments.
- Constructors cannot be virtual.
- They make „implicit calls‟ to the operators new and delete when memory allocation is required.