Topic :Constructor Overloading in C++ Programming Language:

Constructor Overloading

In Our previous tutorial Operator Overloading we discuss about the concept of Overloading, and discuss Operator Overloading. in this tutorial we will discuss about Constructor Overloading in C++ Programming.





Constructor is a Special Method of a Class which will Invoke Automatically whenever Object of Class is Created. The constructor is Responsible for Object Initialization and Memory Allocation of Its Class. If We create any Class without constructor, the compiler will Automatically Create one Default Constructor for the class.




Constructor Overloading is a Technique to create Multiple Constructors with different Arguments. It Allows us to use a single class in many different ways. A same class may behave different type based on constructors overloading. Let's have a example to know, how exactly we can overload constructor, and why we need it.


/* Example - Constructor Overloading - InfoBrother:*/
 
#include<iostream>
using namespace std;
 
class Overloading
{
   private:
	//Private Members:
	string name;
	string Day;
	int temp;
 
   public:
	//Public Members:
	Overloading() // default constructor:
	{
	   name = "Abbottabad";
	   temp = 29;
	   cout<<name<<" Yesterday Temperature: "<<temp<<"°"<<endl;
	}
 
	//Constructor Overloading using Parameters.
	Overloading(string nam, int tem ) 
	{
	   name = nam;
	   temp = tem;
	   cout<<name<<" Today Temperature: "<<temp<<"°"<<endl;
	}
 
	//Constructor Overloading again using more parameters.
	Overloading(string nam, string day, int tem ) 
	{
	   name = nam;
	   temp = tem;
	   Day  = day;
	   cout<<name<<" "<<Day<<" Temperature: "<<temp<<"°"<<endl;
	}			
};
 
main()
{
   //Object Creation:
   Overloading obj1;
   Overloading obj2("Abbottabad", 28);
   Overloading obj("Abbottabad","Monday", 26);
 
   return 0;
}
 


In Above Example, we have created three constructor. The first one is default constructor having no Parameters. The second one is Overloaded Constructor with some parameters. And at the last, we overload Constructor again with different numbers of parameters.

Creating an Overloaded constructor is a simple, same as Overloaded Functions. we can overload constructor as many times as we need. But each constructor must have different arguments list.










I Tried my Best to Provide you complete Information regarding this topic in very easy and conceptual way. but still if you have any Problem to understand this topic, or do you have any Questions, Feel Free to Ask Question. i'll do my best to Provide you what you need.

Sardar Omar.
InfoBrother





Advertising

Advertising