Possible Duplicate:
Initializing in constructors, best practice?
Advantages of using initializer list?
I have the following two ways to define the constructor in the Point Class :
class Point
{
public :
Point(double X,double Y):x(X),y(Y){}
Private :
double x,y;
}
Another way :
class Point
{
public :
Point(double X,double Y)
{
x= X;
y = Y;
}
Private :
double x,y;
}
I want to know which one is better and why?Is there is the use of copy ctor in the first case?
Where each one is preferred?Can some explain with the example?
Rgds,
Softy
The second version does an assignment to the data members, whereas the first initializes them to the given values. The first version is preferred here. Although it may make little difference in the case of doubles, there is no reason at all to prefer a construction that performs extra operations. If your data members were not doubles, but types that are expensive to construct, you would be paying the penalty of default constructing them, and then assigning a value to them.
Example: