Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialization lists in constructor

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;

}
like image 736
user767451 Avatar asked Sep 10 '11 20:09

user767451


2 Answers

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.

like image 128
Oliver Charlesworth Avatar answered Sep 19 '22 10:09

Oliver Charlesworth


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

like image 44
Alok Save Avatar answered Sep 22 '22 10:09

Alok Save