Reputation: 53
I've heard that the advantage of using initialization lists in constructor would be that there will be no extra copies of class type objects. But what does it mean for the following code in class T constructor? If i comment the assignment and use initialization lists what would be the difference?
#include <iostream>
using std::cout;
using std::endl;
using std::ostream;
class X {
public:
X(float f_x = 0, float f_y = 0):x(f_x), y(f_y) {}
~X() {}
X(const X& obj):x(obj.x), y(obj.y) {}
friend ostream& operator << (ostream &os, X &obj);
private:
float x;
float y;
};
ostream& operator << (ostream &os, X &obj)
{ os << "x = " << obj.x << " y = " << obj.y; return os;}
class T {
public:
T(X &obj) : x(obj) { /* x = obj */ }
~T() { }
friend ostream& operator << (ostream &os, T &obj);
private:
X x;
};
ostream& operator << (ostream &os, T &obj)
{ os << obj.x; return os; }
int main()
{
X temp_x(4.6f, 6.5f);
T t(temp_x);
cout << t << endl;
}
Upvotes: 5
Views: 1409
Reputation: 206646
If you use Assignment, then:
x
will be default constructed first &
then assigned with obj
.
The cost is, Default Construction + Assignment
If you use Member initializer list then:
x
will be constructed and initialized with obj
.
The cost is, Construction only
Upvotes: 5
Reputation: 272802
It's exactly what you already said. If you don't use the initializer list, then the default constructor will get called first, and then the assignment operator will get called.
In your example, this is relatively benign (the compiler may even optimise this, I think). But in other cases, it's simply not possible to avoid the initializer list. Imagine if X
didn't have a public assignment operator.
Upvotes: 6
Reputation: 81409
T(X &obj) : x(obj) {}
will copy construct x from obj, while
T(X &obj){ x = obj; }
will construct a default x, only to then replace it with the values from obj.
If you intent to construct a member object, you should do it in the initialization list.
Upvotes: 2