4

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;
    }
};
Community
  • 1
  • 1
cppcoder
  • 22,227
  • 6
  • 56
  • 81

2 Answers2

6

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.
B. Decoster
  • 7,723
  • 1
  • 32
  • 52
5

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:

Community
  • 1
  • 1
Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • +1. Although for "int" members the effect is the same. – Nemo Jul 13 '11 at 16:56
  • In the second, there is only default initialization for types with a non-trivial default constructor. Otherwise, there is no initialization. – James Kanze Jul 13 '11 at 16:58
  • @James: In this example, the types of `x` and `y` is `int`, hence its default-initialization. But your comment makes it more complete. Let me add it to my answer. – Nawaz Jul 13 '11 at 17:00
  • @Nawaz In this example, the types are `int`, which is a POD, so there is no initialization. (But you got it right in the modification of your response.) – James Kanze Jul 14 '11 at 08:51