Search code examples
c++member-initialization

Memberwise Initialization


Possible Duplicate:
C++ initialization lists

What is the difference between member-wise initialization and direct initialization in a class? What is the difference between the two constructors defined in the class?

class A
{
    public:
    int x;
    int y;
    A(int a, int b) : x(a), y(b)
    {}

    A(int a, int b)
    {
        x = a;
        y = b;
    }
};

Solution

  • The theoretical answers have been given by other members.

    Pragmatically, member-wise initialization is used in these cases :

    • You have a reference attribute (MyClass & mMyClass) in your class. You need to do a member-wise initialization, otherwise, it doesn't compile.
    • You have a constant attribute in you class (const MyClass mMyClass). You also need to do a member-wise initialization, otherwise, it doesn't compile.
    • You have an attribute with no default constructor in your class (MyClass mMyClass with no constructor MyClass::MyClass()). You also need to do a member-wise initialization, otherwise, it doesn't compile.
    • You have a monstruously large attribute object (MyClass mMyClass and sizeof(MyClass) = 1000000000). With member-wise initialization, you build it only once. With direct initialization in the constructor, it is built twice.