Использование параметра и переменной-члена в конструкторе

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?

7 голосов | спросил Lukas 7 FebruaryEurope/MoscowbFri, 07 Feb 2014 15:10:52 +0400000000pmFri, 07 Feb 2014 15:10:52 +040014 2014, 15:10:52

0 ответов


Похожие вопросы

Популярные теги

security × 330linux × 316macos × 2827 × 268performance × 244command-line × 241sql-server × 235joomla-3.x × 222java × 189c++ × 186windows × 180cisco × 168bash × 158c# × 142gmail × 139arduino-uno × 139javascript × 134ssh × 133seo × 132mysql × 132