+ 1

Can we have more than one constructors in a class?

9th Dec 2016, 6:03 PM
Mock
Mock - avatar
3 Respostas
+ 6
You can have many, as long as they don't have the same parameters and in the same order in the signature. I think there are three known types: ° Default (in which you inicialize everything with a default value ) °Common (some are passed through parameters and others as in Default) ° Complete (of full I guess, I learned in Spanish) in which you don't inicialize anything with a default value, you use the parameters.
9th Dec 2016, 7:37 PM
C.E.
C.E. - avatar
+ 2
We can have more than one constructor in a class, as long as each has a different list of arguments. #include<iostream> using namespace std; class Point { private: int x, y; public: // Two constructors Point(int x1, int y1) { x = x1; y = y1; } Point() {x = 0; y = 0; } int getX() { return x; } int getY() { return y; } }; int main() { Point p1(10, 15); // first constructor is called here Point p2; // Second constructor is called here // Let us access values assigned by constructors cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY(); cout << "\np2.x = " << p2.getX() << ", p2.y = " << p2.getY(); return 0; } output : p1.x = 10, p1.y = 15 p2.x = 0, p2.y = 0
9th Dec 2016, 6:06 PM
Mock
Mock - avatar
0
Yes Your default and non default constructors.
9th Dec 2016, 6:55 PM
JENN
JENN - avatar