1

I've seen c++ class constructors initialize members in two different ways, but with the same effect. Suppose we have a simple class:

class myClass
{
public:
    myclass();//default constructor

private:
    int a;
    int b;
    bool c;
};

Case 1:

myClass::myClass()
/* Default constructor */
{
    a=5;
    b=10;
    c=true;

    //do more here
}

Case 2:

myClass::myClass()
/* Default constructor */

    :a(5),
    b(10),
    c(true)
{
    //do more in here
}

What is the difference between the two after it compiles? Even if there is no difference, is there a "preferred" way of doing it?

ayane_m
  • 962
  • 2
  • 10
  • 26
  • No difference as both do the same thing. Preference is up to you to decide. Personnally I prefer the second one – smac89 Oct 03 '13 at 02:15
  • 2
    whenever possible prefer case 2. Using initialization list is always optimal. – Arun Oct 03 '13 at 02:26

1 Answers1

3

First constructor calls default constructor of a,b,c first(basically assign them to random value) then assigns them to the provided value. Second constructor directly calls the appropriate constructors for a,b,c.

In general, second constructor is more efficient as members are initialized once, also if you have members without default constructor, you have to initialize them that way or with non-static member initializer in C++11.

yngccc
  • 5,594
  • 2
  • 23
  • 33
  • combine that with the fact that some types *can't* be reassigned, and it becomes clear that the second approach is far better – Ben Voigt Oct 03 '13 at 03:59