Constructor Overloading in C++


As we know function overloading is one of the core feature of the object oriented languages. We can use the same name of the functions; whose parameter sets are different. Here we will see how to overload the constructors of C++ classes. The constructor overloading has few important concepts.

  • Overloaded constructors must have the same name and different number of arguments
  • The constructor is called based on the number and types of the arguments are passed.
  • We have to pass the argument while creating objects, otherwise the constructor cannot understand which constructor will be called.

Example

 Live Demo

#include <iostream>
using namespace std;

class Rect{
   private:
   int area;
   public:
   Rect(){
      area = 0;
   }
   Rect(int a, int b){
      area = a * b;
   }
   void display(){
      cout << "The area is: " << area << endl;
   }
};

main(){
   Rect r1;
   Rect r2(2, 6);
   r1.display();
   r2.display();
}

Output

The area is: 0
The area is: 12

Updated on: 30-Dec-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements