SFML community forums

Help => General => Topic started by: enderboy768 on June 10, 2017, 03:27:30 pm

Title: Difference of passing a * parameter and a & parameter
Post by: enderboy768 on June 10, 2017, 03:27:30 pm
I was reading a tutorial on the internet about game states and then they showed a class of game state with these functions in it:

Code: [Select]
class CGameEngine
{
public:
//... some functions

  void ChangeState(CGameState* state);
  void PushState(CGameState* state);

private:
  // the stack of states
  vector<CGameState*> states;
//... some variables
};


My question is, why is the changeState and pushState need a parameter with *? I thought you would use the & symbol if you want to pass the actual object/variables instead of the copy. Is there any difference? Thank you in advance!  ;D
Title: Re: Difference of passing a * parameter and a & parameter
Post by: korczurekk on June 10, 2017, 03:31:15 pm
Pointers are hairly and C-styled, now kept in c++ mostly for C compatibility. There is no big difference despite that you need std::reference_wrapper to keep references in std::vector.
Title: Re: Difference of passing a * parameter and a & parameter
Post by: enderboy768 on June 10, 2017, 03:35:17 pm
So you mean the function would also work if I changed the * in changeState and pushState parameter to the & symbol?
Title: Re: Difference of passing a * parameter and a & parameter
Post by: eXpl0it3r on June 10, 2017, 04:08:45 pm
Yes, but why don't you just try it out?

As for tutorials on the internet, keep in mind that there are tons of outdated or just bad design/style wise.
So just because you find something somewhere, doesn't mean it's necessarily a recommended practice.
Title: Re: Difference of passing a * parameter and a & parameter
Post by: Elias Daler on June 10, 2017, 05:24:03 pm
I'll recommend using as much references as possible as they can't be null, memory can't get deleted accidentally. I find "obj.someFunc()" easier to read than "obj->someFunc()". std::reference_wrapper is indeed nice and may add some additional semantic to your code, it's explicit way of saying that you keep a reference, not a raw owning pointer.