Initialization Lists in the Constructor

I heard that the advantage of using initialization lists in the constructor will be that there will be no additional instances of objects of the class type. But what does this mean for the following code in the constructor of class T? If I comment on the purpose and use initialization lists, what's 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;

}
+5
source share
3 answers

This is exactly what you already said. If you are not using a list of initializers, the default constructor will be called first, and then the assignment operator will be called.

( , ). . , X .

+6

, :
x &
obj.

+


Member, :
x obj.

<

+5
T(X &obj) : x(obj) {}

x obj,

T(X &obj){ x = obj; }

x, obj.

-, .

+2

All Articles