5

I have recently taken a project with another developer, and he has a certain way of initializing his references.

class Player
{
    private:
        Console &console;
        Armor &armor1, &armor2;
        Debugger &debugger;
        sf::RenderWindow &window;
        sf::Event &event;

   public:
       Player(Console &console, Armor &armor1, ...) : console(console), armor1(armor1), ... {};
}

And it's perfectly fine with me, but what if we add new stuff? Our constructor is massive, and so messy, I would like to know if there are better ways of initializing your references if you have a large project, because if we keep up with this, eventually our constructor will have more lines of code than what it actually does.

Bugster
  • 4,013
  • 8
  • 37
  • 44
  • 2
    no smart pointers? – ratchet freak Jul 27 '13 at 17:14
  • 5
    `Our constructor is massive` Hum... Isn't the class too big for its own good? Perhaps it's time to revisit the design of that class. To answer the question: this initialization code is the recommended C++ way to initialize data members. See also http://stackoverflow.com/questions/6822422/c-where-to-initialize-variables-in-constructor. – Christian Garbin Jul 27 '13 at 19:42
  • that is the only way to initialize references – BЈовић Jul 29 '13 at 05:48
  • Related: [Should I use Dependency Injection or static factories?](https://softwareengineering.stackexchange.com/questions/190120/should-i-use-dependency-injection-or-static-factories). I think my answer there can be applied here as well. – Doc Brown Feb 25 '22 at 13:48

3 Answers3

5

Members of reference types can only be initialized in the initializer list in constructor, because references cannot be rebound. So they have to be initialized in constructor like you wrote. It's the only way.

Which brings up two points:

  1. Isn't the class too big?
  2. Are they really all injected dependencies to be held by reference? A "Player" class looks more like it should own things like "Armour". That is hold it by (preferably smart) pointer and construct it itself.
Jan Hudec
  • 18,250
  • 1
  • 39
  • 62
0

C++ 11 allows initialization in the class declaration itself.

However, if you need to initialize from outside sources, that won't help.

You can also initialize on an 'as needed' basis - don't have to do it all at once in the constructor, but in the call that actually uses the reference - each reference at its appropriate time.

This depends on your design of course, but is often a good way to avoid those ugly massive constructors.

Vector
  • 3,180
  • 3
  • 22
  • 25
0

Your method is a good way to initialise properties in c++.

Please note the order of properties initialise.

If you use C struct,you can use:

struct Obj   
obj={.a="a",.b="b"}; 

to init all properties.

I think that C is better than C++.
C++ has many traps.

Ben McDougall
  • 716
  • 5
  • 17
Edward Shen
  • 139
  • 6