0

Possible Duplicate:
What is this weird colon-member syntax in the constructor?

Hi, I recently came across this syntax in a C++ program. This is not passing parameters to a base class constructor as I know what that looks like and how to code it. This looks like some sort of variable initialization for the class... Here is the code:

class Particle
{
private:
  bool movable;
  float mass;
  Vec3 pos;
  Vec3 old_pos; 
  Vec3 acceleration;
  Vec3 accumulated_normal;
public:
  Particle(Vec3 pos)
  : pos(pos),
    old_pos(pos),
    acceleration(Vec3(0,0,0)),
    mass(1),
    movable(true),
    accumulated_normal(Vec3(0,0,0))
  {}

  Particle() {}

  // More unrelated code
};
Community
  • 1
  • 1
footy
  • 5,803
  • 13
  • 48
  • 96

2 Answers2

6

Initialisation lists can be used to initialise member variables as well as parents. This is the correct way of writing a constructor - initialisation like this is more efficient than doing assignment in the constructor body, and is likely semantically more correct.

  • +1 It should also be noted that member variables have to be initialised in the order they are declared. – helpermethod Apr 28 '11 at 09:01
  • 2
    @Helper But not in the initialisation list, where order is not significant. –  Apr 28 '11 at 09:02
  • Ah, sry, ofc you are correct. Another reason why to use them :-). – helpermethod Apr 28 '11 at 09:04
  • 5
    @Helper Method: Slightly unclear actually. They *are* initialized in the order they're declared, regardless of the order in which you write them in the initialization list. Thus you probably *should* write them in the order in which they're declared, for clarity. – Stuart Golodetz Apr 28 '11 at 09:04
  • 2
    @Stuart Golodetz: +1. Most compiler actually issue a warning when you don't. – ereOn Apr 28 '11 at 09:07
  • @Stuart This is true, and gcc actually produces an irritating warning if you don't. –  Apr 28 '11 at 09:08
  • @ereOn: It's not always turned on by default :) But most compilers can be made to issue such a warning. – Stuart Golodetz Apr 28 '11 at 09:10
  • To follow on from that, I just tested, and VC++ with warning level 3 (the default) doesn't output such a warning. – Stuart Golodetz Apr 28 '11 at 09:13
3

That's the syntax for member initialization, as you surmised. Contrast this:

class C
{
private:
  int i;
public:
  C(int i_) : i(i_) {} // initialization
};

with:

class C
{
private:
  int i;
public:
  C(int i_) { i = i_; } // assignment
};

It's generally better to initialize members rather than assigning to them in the constructor body, and there are some cases where it's essential (one example would be references).

Stuart Golodetz
  • 20,238
  • 4
  • 51
  • 80