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.

4

3 Answers 3

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.
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.

1
  • 1
    These are refs, not pointers - you have to initialize them in the constructor. Aug 13, 2013 at 12:14
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.