C++ Constructor Overloading

Advertisements

Constructor Overloading in C++

More than one constructor with different signature in a class is called function overloading. Signature of constructor includes :

  • Number of arguments
  • Type of arguments
  • Sequence of arguments

When we create an object, the compiler determines the most appropriate constructor to use by comparing the signature of the statement which is creating object with the signature of specific constructor definition.

Example of constructor overloading


	#include<iostream.h>
	#include<conio.h>
	#include<string.h>

	class Student
	{

		  int Roll;
		  char Name;
		  float Marks;

		  public:

		  Student(int r,char nm[],float mks)           // Constructor 1
		  {
				Roll = r;
				strcpy(Name , nm);
				Marks = mks;
		  }

		  Student(int r,float mks,char nm[])           // Constructor 2
		  {
				Roll = r;
				strcpy(Name , nm);
				Marks = mks;
		  }

		  Student(char nm[],int r,float mks)           // Constructor 3
		  {
				Roll = r;
				strcpy(Name , nm);
				Marks = mks;
		  }

		  void Display()
		  {
				cout<<"\n\t"<<Roll<<"\t"<<Name<<"\t"<<Marks;
		  }

	};


	void main()
	{

		  Student S1(101,"Kumar",78.53);                 //Statement 1
		  Student S2("Sumit",102,89.27);                 //Statement 2
		  Student S3(103,67.38,"Kunal");                 //Statement 3

		  S1.Display();
		  S2.Display();
		  S3.Display();

	}


	Output :

		  101     Kumar     78.53
		  102     Sumit     89.27
		  103     Kunal     67.38

				

In the above example, we have three constructors with different sequence of arguments. Statement 1 will invoke the constructor 1 b'coz the signature of constructor 1 is similar to constructor 1. Similarly Statement 2 will invoke constructor 3 b'coz the signature of statement 2 is similar to constructor 3. Statement 2 is passing three arguments, 1st is of string type (character array) ,2nd is of int type and the third is float type. And constructor 2 is the only constructor which is receiving string as 1st value, int as 2nd value and float as third value.

Advertisement