c++constructorinitializationmember-initializationctor-initializer

What is the difference between initialization and assignment in a constructor?


Let us consider the following classes

struct test1
{
    int a;
    int b;
    test1() : a(0), b(0) {}
};

struct test2
{
    int a;
    int b;
    test2() { a = 0; b = 0; }
};

Now, I know that test1() constructor is the right way to initialize the data members of a class, because in test2() we are performing assignment and not initialization. My questions are:

  1. What might go wrong if we perform assignment instead of initialization?
  2. Doesn't the compiler internally perform assignment in case of test1() constructor? If not, then how are these initialized?

Solution

  • What might go wrong if we perform assignment instead of initialization?

    Some class types (and also references and const objects) can't be assigned; some can't be default-initialised; some might be more expensive to default-initialise and reassign than to initialise directly.

    Doesn't the compiler internally performs assignment in case of test1() constructor? If no then how are these initialized?

    In the case of primitive types like int, there is little or no practical difference between the two. Default-initialisation does nothing, and direct-initialisation and assignment both do essentially the same thing.

    In the case of class types, default-initialisation, assignment and direct-initialisation each call different user-defined functions, and some operations may not exist at all; so in general the two examples could have very different behaviour.