Last updated on:May 26th, 2018,

What is Constructor overloading, Examples and purpose of constructor overloading in C++, OOP

What is Constructor overloading, Examples and purpose of constructor overloading in C++, OOP

In this tutorial, we will learn about the followings;

  1. What is Constructor overloading?
  2. Examples of constructor overloading in C++, OOP
  3. 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?

Line #Code
1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

#include<iostream>

using namespace std;

class numbers_sum

{

public:

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;

}

};

int main()

{

numbers_sum a(3,4);

numbers_sum b(5,5,2);

}

 

Output
Sum of two numbers is =

7

the sum of three numbers are =

12

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

Answer - Click Here:
NO

2. int sum(int a, int b) and another constructor is sum(int a, int b). Here constructor is overloaded? YES / NO

Answer - Click Here:
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

Answer - Click Here:
YES
.

0Shares

Leave a Reply

Your email address will not be published.