Every so often when writing a constructor of a class, I ask myself whether I should be using the initialized member variable or the constructor parameter. Here are two examples to illustrate what I mean:
Constructor Parameter
class Foo {
public:
Foo(int speed) :
mSpeed(speed),
mEntity(speed)
{ }
private:
int mSpeed;
Entity mEntity;
}
Member Variable
class Foo {
public:
Foo(int speed) :
mSpeed(speed),
mEntity(mSpeed)
{ }
private:
int mSpeed;
Entity mEntity;
}
Further more the same issue arises with using variables in the constructor body.
Constructor Parameter
class Foo {
public:
Foo(int speed) :
mSpeed(speed)
{
mMonster.setSpeed(speed);
}
private:
int mSpeed;
Monster mMonster;
}
Member Variable
class Foo {
public:
Foo(int speed) :
mSpeed(speed)
{
mMonster.setSpeed(mSpeed);
}
private:
int mSpeed;
Monster mMonster;
}
I'm aware that it doesn't really matter (except some special cases), that's why I'm rather asking for comments on code design, than what makes it work and what doesn't.
If you need a specific question to work with: What way yields a nice and consistent code design and does one have an (dis)advantage over the other?
Edit: Don't forget the second part of the question. What about variables in the constructor body?