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

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 ().

class Car
{	
public:
	//Constructor
	Car(){		
		
	}	
};

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.

class Car
{
	int id;
	string model;
public:
	//Constructor initializes data members
	Car(){		
		this->id = 11;
		this->model = "Maruti";
	}
	
	void display(){

		cout<< "Car Info:"<<" "<id<<" "<model.c_str()<<"\n";

	}
};
int main(){
	
	Car c;
	c.display();	

	return 0;
}

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

Related Posts