Pergunta

Heyy, I am trying to switch from initialising my variables within the constructor to using the constructor initialiser list.

So instead of writing

Class::Class(int width, int height) {
  this->width = width;
  this->height = height;
}

I am doing this:

Class::Class(int width, int height) : 
  width(width), 
  height(height) {
}

That's all working, but now my problem... Say I have the following constructor:

Class::Class(int width, int height) {
  this->width = width;
  this->height = height;
  this->state.setCurrState(this->state.stateMenu);
  this->state.setPrevState(this->state.getCurrState());
}

"state" is just an object of the class "State" which I create in my header. The functions setCurrState and setPrevState are of the type void and just set the class's private variable.

How do I convert the constructor? I know it is possible to write functions in the initialiser list, but the functions I want to add do not return anything... they are void, so I do not know how I would call them?

Class::Class(int width, int height) :
  width(width), 
  height(height) 
  // call functions here... but how?
  {
}

Thank you so much I hope you can help me <3

Foi útil?

Solução

There is no additional point and advantage to call those functions in initializer list, at least in your case.

Simply call them in the constructor body.


Important note:

You said state is a member of Class. So in constructor's level, state is not constructed yet, then constructing it by itself is somehow meaningless:

state.setCurrState(state.stateMenu);
state.setPrevState(state.getCurrState());

Try to write a well constructor for state's class to set curr/prev to a initial states.

Outras dicas

Easy solution: Leave the initializing functions in the body of the constructor.

Slightly more difficult solution:

  • Add a constructor to State to initialize it from an argument.
  • Write new functions that return the value that you want to pass to the constructor of State.

  • setCurrState and setPrevState are not formally initializing your state object, they are merely changing it's "state" (no pun intended) after it has been initialized.

    If you consider them to be semantically initializing you state object, then you might as well formalize that by incorporating them in state's constructor (which should receive the needed states and set them right away). You can then initialize it in the initializer list.

    Add a function that returns a State:

    State GiveMeAState() {
      State state;
      state.setCurrState(state.stateMenu);
      state.setPrevState(state.getCurrState());
    }
    

    and use it in your initialization list:

    Class::Class(int width, int height) : 
      width(width), 
      height(height),
      state(GiveMeAState()) {
    }
    
    Licenciado em: CC-BY-SA com atribuição
    Não afiliado a StackOverflow
    scroll top