What is constructor in C++ Programming and its purpose?

(Last Updated On: March 17, 2018)

Answer: Constructor in C++  programming of a class is like a member function of a class that have same name as the class name. For example, in below class Animal, constructor name will also be Animal ().

 

The main purpose of the class constructor in C++ programming is to construct an object of the class. In other word, it is used to initialize all class data members.

For example, in below class, constructor Car () is initializing data members with default values. And, when we create the object of a class, this constructor will always be called.

 

 

Note that if we don’t write a constructor in the class, compiler will provide default constructor in C++ programming.

Class constructor is also used for constructor overloading (Read C++ constructor overloading with example ) or to prevent object creation of the class by using private c++ access specifiers , so, the class constructor cannot be accessible from outside world e.g. in main () program or from another classes etc.

Conclusion:

  • Constructor in C++ have same name as class name.
  • Constructor can be used for constructor overloading.
  • Constructor can be used to prevent object creation of the class making it a private.

NOTES:

Types of Constructor in C++ Object Oriented Programming
  • Default Constructor
  • Parametrized Constructor
  • Copy Constructor