C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » C++ programming language

What is the Constructor and its types in C++?

Learn: What is the constructor in C++ programming language? Types of constructors in C++, Explain constructors with examples.

Constructor is the special type of member function in C++ classes, which are automatically invoked when an object is being created. It is special because its name is same as the class name.

Constructor is used for:

  • To initialize data member of class: In the constructor member function (which will be declared by the programmer) we can initialize the default vales to the data members and they can be used further for processing.
  • To allocate memory for data member: Constructor can also be used to declare run time memory (dynamic memory for the data members).

There are following properties of constructor:

  • Constructor has the same name as the class name. It is case sensitive.
  • Constructor does not have return type.
  • We can overload constructor, it means we can create more than one constructor of class.
  • We can use default argument in constructor.
  • It must be public type.

Example:

#include <iostream>

using namespace std;

class Sample
{
	private:
		int X;
	public:
		//default constructor 
		Sample()
		{
			//data member initialization
			X=5;
		}

		void set(int a)
		{
			X = a;
		}

		void print()
		{
			cout<<"Value of X :  "<<X<<endl;
		}
};

int main()
{
	//Constructor called when object created
	Sample S; 

	S.print();
	//set new value
	S.set(10);
	S.print();

	return 0;
}

Output

Value of X :  5
Value of X :  10

Types of constructors in C++

Normally Constructors are following type:

  1. Default Constructor or Zero argument constructor
  2. Parameterized constructor
  3. Copy constructor
  4. Conversion constructor
  5. Explicit constructor

Note:
If we do not create constructor in user define class. Then compiler automatically insert constructor with empty body in compiled code.





Sponsored Links




COMMENTS