0

Hi I am learning how to implement state machine in c++ at the moment, and I don't really understand what I give to my function with this following code :

void promptfornextevent(elevatorstate& state, int event){
   std::cout<<"Current State = "<< state.Description() << std::endl;
}

And I call it like this in the main function :

int main(){
...
elevatorstate* currentstate = new state_1stfloor;
promptfornextevent(*currentstate, event);
...
}

I don't understand the point using reference on the line elevatorstate& state. What exactly does my function receive from the main function? I thought that I give my function an object (pointed by the currentstate)

ptd
  • 29
  • 9
  • 2
    There is a good list of C++ books [here](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – molbdnilo Jan 24 '17 at 08:26
  • It means that the name `state` used inside the `promptfornextevent` function designates the object you allocated by `new` in `main`. (BTW you probably didn't need to use `new` in main). – M.M Jan 24 '17 at 09:01
  • Answered! Thank you sir – ptd Jan 24 '17 at 11:08

1 Answers1

0

To begin with, by passing an argument by reference, you are avoiding an extra copy of the argument getting created. The reference is pointing to the same object which got created in main function.

Had you passed the argument by copy, the copy constructor of elevatorstate would have been called and the return value would have got assigned to the state argument.

Since the same object is being used in the promptfornextevent function, any changes to the object done in promptfornextevent will persist even when you return back to the main function.

Rishi
  • 1,387
  • 10
  • 14