Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memberwise Initialization [duplicate]

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;
    }
};
like image 279
cppcoder Avatar asked Dec 21 '22 11:12

cppcoder


2 Answers

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.
like image 71
B. Decoster Avatar answered Dec 24 '22 00:12

B. Decoster


First one uses initialization and second one does NOT use initialization, it uses assignment. In the second one, the members x and y are default-initialized first (with zero), and then they're assigned with a and b respectively.

Also note that in the second one, members are default initialized only if the types of members are having non-trivial default constructor. Otherwise, there is no initialization (as @James noted in the comment).

Now see this topic to know:

  • What is a non-trivial constructor in C++?
like image 29
Nawaz Avatar answered Dec 24 '22 01:12

Nawaz