I have recently taken a project with another developer, and he has a certain way
ID: 654906 • Letter: I
Question
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.
Explanation / Answer
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:
Isn't the class too big?
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.