Constructor in c++ is a special member function its name is same as the class name.
- The constructor is invoked automatically whenever an object of its associated class is created.
- It is called constructor because it constructs the values of the data member of the class.
- Generally , a constructor should be defined under the public section of a class , so that its object can be created in any function.
types of constructor in c++
there are different types of constructor available in c++.
- Default constructor
The constructor that accept no parameter is called default constructor.
If a class has no explicit constructor defined , the compiler will supply a default constructor.
The default constructor provided by the compiler does not do anything specific. It simply allocates memory to data members of object.
2. parameterized constructor
The constructor that can take arguments are called parameterized constructor.
Declaring a constructor with arguments hides the default constructor.
Characteristics of constructor in c++
- They should be declared in the public section.
- They are invoked automatically when the objects are created.
- They do not have return (data type) type not even void and there for they cannot return any values.
- They can not be inherited, the a derived class can call the base class constructor.
- They make implicit calls to the operator new and delete when memory allocation is required.
- It is not possible to take the address of a constructor.
- An object of a class with a constructor cannot be a member of a union.
Constructors and destructors have no return type, not even void.
A constructor for a class is needed so that the compiler automatically initializes an object as soon as it is created. A class constructor, if defined , is called whenever a program creates an object of that class.
Before the release of c++11 standard of C++, constructors of a class were not allowed to call other constructor had to construct all of its class members itself. But C++11 standard allows constructors of the same class.