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

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

What is Constructor overloading?

Different constructors with the same name are called constructor overloading.

The constructor must obey one or both of the following rules.

  1. All constructors with the same name have a different number of parameters.
    • numbers_sum(int n1, int n2) and another constructor as numbers_sum(int n1, int n2, int n3).
  2. All constructors with the same name and have the same number of parameters but of different data types.
    • numbers_sum(int n1, int n2) and another constructor as numbers_sum(float n1, float n2).

Example of constructor overloading

Example of constructor overloading with a different number of parameters and constructors with the same name.

Output

Sum of two numbers is =
7
the sum of three numbers is =
12

Example of constructors with the same name and have the same number of parameters but of different data types.

Output

Sum of two numbers is =

7

the sum of three numbers is =

10

Another Example of Constructor Overloading In C++

Output

I am Constructor

Im Constructor

Values :33      +7=40

Values :3      +7=10

Constructor Outside the Class

The Syntax for Constructor Outside the Class

class class_name {
public:
//Constructor declaration
class_name();

//… other Variables & Functions
}

// Constructor definition outside Class
class_name::class_name() {
// Constructor code
}

Program of Constructor Outside the Class

Copy Constructor

A copy constructor is just like a normal Constructor with the parameters, but this parameter is the same class object. The Copy constructor uses to initialize an object using another object of the same class.

C++ Program of Copy Constructor

What are the advantages of constructor overloading?

  1. It acts as compile-time polymorphism.
  2. Objects can be constructed in different ways.
  3. 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

Topic Covered

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

By: Prof. Fazal Rehman Shamil    CEO @ T4Tutorials
Whatsapp: +92 302 87 000 85     Facebook: For Discussions

Leave a Reply

Your email address will not be published. Required fields are marked *