C++ is an Object-Oriented Programming Language that is widely used today in the IT industry all over the world. It is a foundational programming language that supports the OOPs Concepts, it was created in 1979 by Bjarne Stroustrup at AT&T Bell Labs. In C++, we can have many constructors in a class with the same name as long as each constructor has a different set of parameters. This concept is famously known as Constructor Overloading in C++ and is very much similar to function overloading in C++. We will dive deep into this concept and understand what exactly Constructor Overloading in C++ means. Before that let’s see what is a constructor in brief.
What is a Constructor in C++?
A constructor is a special type of method in a class that is called when an object of that class is created. The main objective of a constructor is to initialize all the data members of a class to default value(set to zero) when an object of that class is created. A constructor must have the same name as the class and it does not have a return type, not even void.
Types of Constructors
There are three types of constructors:-
- Default Constructor
- Parameterized Constructor
- Copy Constructor
What is Operator Overloading in C++?
The concept of defining multiple constructors for a class with different parameters is known as constructor overloading in c++. In simple words, a class can have more than one constructor, each constructor has its own different set of distinct parameters. Constructor overloading allows a class to be initialized in a variety of ways based on the requirements of the user.
Here are some examples of valid and invalid constructor overloading in c++:
-
Multiplication(int x, int y) and Multiplication(double x, double y) – This can be considered a valid example of constructor overloading.
-
Addition(int x, int y) and Addition(int x, double y) – This is a valid example of constructor overloading.
-
Subtraction(float x, float y) and Subtraction(float x, float y) – This is a invalid example of constructor overloading.
-
Addition(int x, int y) and Addition(int x, int y, int z) – This can be considered a valid example of constructor overloading.
How to Declare Constructor Overloading in C++
Here is the Syntax of Constructor Overloading in C++:
class ClassName {
public:
ClassName() {
// Constructor with no parameter.
}
ClassName(int x, double y) {
// Constructor with two parameters.
}
ClassName(int x, char y, float z) {
// Constructor with three parameters.
}
ClassName(ClassName & object) {
// Constructor with the same class object as a parameter.
}
// Other member functions.
};
Examples of Constructor Overloading in C++
Let’s see some examples of constructor overloading in c++
Example 1 of Constructor Overloading in C++
Here is a C++ program to overload two constructors.
#include <iostream> using namespace std; class Person{ private: string Name; int Age; public: // This is a Constructor with no parameters. Person() { Name = "Anoop"; Age = 25; } // This is a Constructor with two parameters. Person(string str, int x) { Name = str; Age = x; } // Member functions declaration. string get_Name() { return Name; } int get_Age() { return Age; } }; int main() { Person p1, p2("PrepBuddy", 28); cout << "Name: " << p1.get_Name() << " Age: " << p1.get_Age() << endl; cout << "Name: " << p2.get_Name() << " Age: " << p2.get_Age() << endl; return 0; }
Output:
Name: Anoop Age: 25
Name: PrepBuddy Age: 28
Explanation: In the above C++ program, we have created a class with the name Person which contains two variables i.e Name and Age. We have also defined two constructors, Person() and Person(string str, int x). The first constructor is called when we create object p1 because we have not passed any parameter. The second constructor is called when we create object p2 because we have passed two parameters(i.e str and x) with it. The get_Name() and get_Age() methods return the Name and Age, which we use to print the name and age of objects p1 and p2.
Example 2 of Constructor Overloading in C++
Here is a C++ program to overload three constructors.
#include <iostream> using namespace std; class Area { private: // Member Variable Declaration. int area; public: // This is a Constructor with no parameters. Area() { area = 0; } // This is a Constructor with one parameters. Area(int side) { area = side * side; } // This is a Constructor with two parameters. Area(int length, int width) { area = length * width; } // Member function declaration. int disp() { return area; } }; int main() { Area point; Area square(5); Area rectangle(6, 9); cout << "Area of point: " << point.disp() << endl; cout << "Area of square: " << square.disp() << endl; cout << "Area of rectangle: " << rectangle.disp() << endl; return 0; }
Output:
Area of point: 0
Area of square: 25
Area of rectangle: 54
Explanation: In the above C++ program, we have created a class with the name Area which contains only one variable i.e, area. Inside our class we have defined three constructors, Area(), Area(int side), and Area(int length, int width). The first constructor, Area(), is called when we create object point because we have not passed any parameter. The second constructor, Area(int side), is called when we create object square because we have passed one parameter(i.e, side). The third constructor, Area(int length, int width), is called when we create object rectangle because we have passed two parameters(i.e, length and width) with it.
Advantages of Using Constructor Overloading in C++
Listed Below are some advantages of using constructor overloading in C++:
-
Because of constructor overloading, inside a class we can declare multiple constructors with different parameters, this helps in providing flexibility in terms of how objects of that class can be created.
-
Constructor overloading helps us reuse the code by invoking one constructor from another constructor of the same class, this results in the reduction of code duplication and makes the maintenance of code very easier for us.
-
We can optimize the efficiency of our program by avoiding unnecessary initialization and by minimizing the chances of errors by implementing constructor overloading.
Disadvantages of using Constructor Overloading in C++
While constructor overloading provides several advantages, there are also some potential disadvantages that we must consider before overloading a constructor:
-
Has a Confusing and complex syntax which makes it more difficult to understand and maintain the code.
-
Each overloaded constructor adds more code to the class which can increase the size of the executable file and makes the program run slower.
-
It makes the debugging process difficult because multiple constructors are used. So, it is kinda hard to identify the source of the error.
Summary
- A constructor is a special type of member function that is invoked when an object of that class is created.
- A constructor has three types – Default constructor, Parameterized constructor, and copy constructor
- When a class in c++ has multiple constructors with different parameters so that every constructor of the class can perform a different task. This is defined as constructor overloading in c++.
- The advantage of constructor overloading is it provides flexibility in creating multiple types of objects for a class.
- The disadvantage of constructor overloading is that it has a confusing syntax and it makes the debugging process more difficult to perform.
FAQs
Here are some frequently asked questions on constructor overloading in c++.
Q1: Is it possible for a constructor to be private?
Ans: Yes, it is possible for a constructor to be private in C++. A private constructor is useful for implementing the Singleton design pattern which states that a class should only have one instance. By making the constructor private, it is not possible to instantiate the class from outside and the Singleton instance can be controlled.
Q2: Can a constructor call another constructor of the same class?
Ans: Yes, using the constructor initialization list, a constructor can call another constructor of the same class. This is referred to as constructor chaining. It enables a constructor to reuse code from another constructor in the same class, making the code more concise and easier to maintain.
Q3: Can a constructor be virtual in C++?
Ans: Yes, a constructor in C++ can be virtual. But it is not advised to declare a constructor virtual because virtual functions are resolved at runtime, and the constructor is used during object construction before the virtual function table is set up. This results in unexpected behavior and must be avoided.
Q4: In C++, can a constructor throw an exception?
Ans: Yes, in C++, a constructor can raise an exception. If a constructor fails to properly initialize an object, it can throw an exception to signal the problem. But it should be done with caution because it is very much possible that the object may not be entirely built at the time the exception is thrown.