C++ constructor style

Status
Not open for further replies.
code:<HR>
Code:
class Monkey {
public:
    int eyes;<P>    Monkey();
    Monkey(int eyes);
};

Now with that header definition why would someone set up their constructors like...

code:<HR>
Code:
Monkey::Monkey() : eyes(2)
{
}<P>Monkey::Monkey(int e) : eyes(e)
{
}

instead of...

code:<HR>
Code:
Monkey::Monkey()
{
    eyes = 2;
}<P>Monkey::Monkey(int e)
{
    eyes = e;
}

??? Sure, I guess you can save a line, but it starts to get hard to read if you initalize a bunch of variables like so...

code:<HR>
Code:
Monkey::Monkey(int eyes, int ears, int toes) : eyes(eyes), ears(ears), toes(toes)
{
}

The only thing I can think of is to make something like so clear...

code:<HR>
Code:
Monkey::Monkey(int eyes, int ears, int toes) : eyes(eyes), ears(ears)
{
    this->toes = 6;
}


Thanks.
~Kevin
:)
 
Initialization is faster than assignment.

The list after the parameter list but before the braces is an initialization list. It means that when the values are created, they're created correctly in the first place.

Using assignment within the body of the function means that first the variables are created, then they're set to the value you want (rather than just being created correctly in the first place).

It doesn't really matter for simple types, but a class could have a marked difference in its behaviour.
 

sevensor

Wise, Aged Ars Veteran
109
Also, this kind of initialization is the only way to set the value of constant member variables. For example:
code:<HR>
Code:
class class1
{
  private:
  const int int1;<P>  public:
  class1();
  class1(int initval);
};<P>class1::class1() 
{
  int1=15;  //compile error:  assignment of read-only data member
}<P>class1::class1(int initval) : int1(initval)
{;}<P>
 
??? Sure, I guess you can save a line, but it starts to get hard to read if you initalize a bunch of variables like so...
You can split them on several lines you know.... I usually write something like:
code:<HR>
Code:
MyClass::MyClass(int v1, int v2, int v3, int v4)
  : m1(v1), m2(v2), m3(v3), m4(v4)
{
}
... splitting the declaration of the function and the initialization of the members. If they add up to more than a short line (60-80 characters), I'll split them into several lines:
code:<HR>
Code:
MyClass::MyClass(...)
  : SomeMemberWithALongName1(initializerWithAnInsanelyLongName1),
    SomeMemberWithALongName2(initializerWithAnInsanelyLongName2),
    SomeMemberWithALongName3(initializerWithAnInsanelyLongName3),
    SomeMemberWithALongName4(initializerWithAnInsanelyLongName4)
{
}

Edit: PeterB and sevensor covered most of the reasons to construct this way, but there is another one: it's the only way to construct a base class with something other than the default constructor. For example:
code:<HR>
Code:
class A
{
public:
    A(int) {}    // the int is unused here
};<P>class B : public A
{
public:
    B() : A(10) {}
}
 
Status
Not open for further replies.