Could someone explain this C++ syntax? [duplicate]
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
};
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.
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).
精彩评论