logo codesdope

Constructor overloading


Suppose we have a 'Student' class and while making its object, we want to pass a name of it and if nothing is passed then the name should be "unknown". And yes! we can do this by having two constructors.

#include <iostream>
#include <string>

using namespace std;

class Student
{
	string name;
	public:
		Student( string n )
		{
			name = n;
		}
		Student()
		{
			name = "unknown";
		}
		void printName()
		{
			cout << name << endl;
		}
};

int main()
{
	Student a( "xyz" );
	Student b;
	a.printName();
	b.printName();
	return 0;
}
Output
xyz
unknown

And it is working!

This is called constructor overloading.

Now let's understand this example. Here, we made two objects of class 'Student'. While creating an object 'a', we passed a string "xyz" to the object as Student a( "xyz" );. This invoked the constructor having a string parameter Student( string n ).

Similarly, while creating a second object 'b' of the class Student, we didn't pass anything to the object 'b' as Student b;. So, the constructor having no parameter Student() got invoked and initialized the name with the value unknown.

Condition for constructor overloading


The one condition for constructor overloading is that both the constructors must have different parameters. Like in the above example, in the first constructor, we passed one String and in the second, nothing.

We can't make two constructors having exactly same arguments( e.g.- both having two ints ).

Either number of argument or type of argument must vary.

We can have any number of constructors but with different arguments.

Don't let your dreams be dreams.
-Jack Johnson

Share what you know
Doubt? Ask question
Close

Welcome.please sign up.

Close

Welcome.please login.