Skip to content
Related Articles

Related Articles

Improve Article

Constructor Overloading in C++

  • Difficulty Level : Basic
  • Last Updated : 28 Jun, 2021

Prerequisites: Constructors in C++ 
In C++, We can have more than one constructor in a class with same name, as long as each has a different list of arguments.This concept is known as Constructor Overloading and is quite similar to function overloading
 

  • Overloaded constructors essentially have the same name (exact name of the class) and differ by number and type of arguments.
  • A constructor is called depending upon the number and type of arguments passed.
  • While creating the object, arguments must be passed to let compiler know, which constructor needs to be called. 
     

 

CPP




// C++ program to illustrate
// Constructor overloading
#include <iostream>
using namespace std;
 
class construct
{
 
public:
    float area;
     
    // Constructor with no parameters
    construct()
    {
        area = 0;
    }
     
    // Constructor with two parameters
    construct(int a, int b)
    {
        area = a * b;
    }
     
    void disp()
    {
        cout<< area<< endl;
    }
};
 
int main()
{
    // Constructor Overloading
    // with two different constructors
    // of class name
    construct o;
    construct o2( 10, 20);
     
    o.disp();
    o2.disp();
    return 1;
}

Output: 

0
200
 

Related Articles : 
 

This article is contributed by I.HARISH KUMAR. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :