Reputation: 880
I have the following code:
#include <iostream>
using namespace std;
struct Point {
double x,y;
Point(double x=0, double y=0): x(x), y(y) {}
};
struct Triangle {
Point A,B,C;
Triangle(Point A=Point(), Point B=Point(), Point C=Point()): A(A), B(B), C(C) {}
void output()
{
cout<<"A: "<<A.x<<";"<<A.y<<endl;
cout<<"B: "<<B.x<<";"<<B.y<<endl;
cout<<"C: "<<C.x<<";"<<C.y<<endl;
}
};
int main() {
Triangle t;
t.output();
return 0;
}
Everything works fine. My question is about the Triangle
constructor with default parameters. Is this a correct way to initialize the members by calling the Point
constructor like this Point A=Point()
(in terms of efficiency and clean code)?
Upvotes: 0
Views: 52
Reputation: 206567
Is this a correct way to initialize the members by calling the Point constructor like this Point A=Point() (in terms of efficiency and clean code)?
It is correct.
You can't talk about efficiency with just one method. You need to present a second method and then compare them for efficiency.
As far as cleanliness is concerned, I think it is better to use function argument names that are different than member variables.
The compiler will create correct code when you use
Triangle(Point A=Point(), Point B=Point(), Point C=Point()): A(A), B(B), C(C) {}
but it is more human readable to use
Triangle(Point inA = Point(), Point inB = Point(), Point inC = Point()): A(inA), B(inB), C(inC) {}
Upvotes: 2
Reputation: 4276
In terms of code cleanliness I would prefer to present two constructors instead:
Triangle(Point inA, Point inB, Point inC): A(inA), B(inB), C(inC) {}
Triangle() : Triangle(Point(), Point(), Point()) {}
Upvotes: 2