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;
}
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.