What is Constructor overloading, Examples and purpose of constructor overloading in C++, OOP
In this tutorial, we will learn about the followings;
- What is Constructor overloading?
- Examples of constructor overloading in C++, OOP
- The purpose of constructor overloading in C++, OOP
What is Constructor overloading?
Different constructors with the same name are called constructor overloading. But all constructors with the same name have a different number of parameters.
Give an example of constructor overloading?
using namespace std;
numbers_sum(int n1, int n2)
cout<<“sum of 2 numbers is = “<<endl<<n1+n2<<endl;
numbers_sum(int n1, int n2, int n3)
cout<<“sum of 3 numbers is = “<<endl<<n1+n2+n3<<endl;
|Sum of two numbers is =|
the sum of three numbers are =
In this program numbers_sum on line 6 and 10 are two constructors because they have the same name as the class name in line 3 and both constructors have a different number of parameters. The first constructor on line 6 has two parameters and the second constructor on line 10 have three constructors.
What are advantages of constructor overloading?
- It acts like a compile time polymorphism.
- Objects can be constructed in different ways.
- Helpful when we are programming the big problem because it is easy to remember the constructor name if many constructors are with the same name.
|Test Your Understandings|
1. Constructor overloading means different function name same number of parameters and with same data types? YES / NO
2. int sum(int a, int b) and another constructor is sum(int a, int b). Here constructor is overloaded? YES / NO
3. int sum(int a, int b) and another constructor is sum(int a, int b, int c). Here constructor is overloaded? YES / NO.