+ 1

What is constructor overloading in CPP?

https://www.sololearn.com/discuss/2052876/?ref=app

1st Nov 2019, 4:01 AM
Komal
Komal - avatar
4 Antworten
+ 8
Constructor overloading is a concept of having more than one constructor with different parameters list Example: #include <iostream> using namespace std; class ABC { private: int x,y; public: ABC () { x = y = 0; } ABC(int a) { x = y = a; } ABC(int a,int b) { x = a; y = b; } void display() { cout << "x = " << x << "y = " << y <<endl; } }; int main() { ABC cc1; cc2(10); cc3(10,20); cc1.display(); cc2.display(); cc3.display(); return 0; }
1st Nov 2019, 4:36 AM
Rohitman
Rohitman - avatar
+ 3
Komal Please avoid inclusion of links having no relevance to the main question. The linked question subject was about structure not class constructor : )
1st Nov 2019, 8:58 AM
Ipang
+ 1
See when you create a class, then the default constructor is also created by itself. To overload a constructor you just have to pass different parameters or no parameters for eg- class Number{ public: int x,y; Number(int x, int y){ this.x = x; this.y = y; } // Default constructor Number(){ cout << "I print numbers" << endl; } // Constructor overloaded } So in the main method when you try to create an instance of the class then don't pass any parameter to it and it will ultimately call the overloaded constructor. Always remember that the constructor is called when an object is created of that class.
1st Nov 2019, 4:27 AM
Avinesh
Avinesh - avatar
0
Rohit Gupta💻 What is the type of variable <cc2> and <cc3>? why you didn't specify the type for these objects?
1st Nov 2019, 8:55 AM
Ipang