Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Difference of passing a * parameter and a & parameter  (Read 2284 times)

0 Members and 1 Guest are viewing this topic.

enderboy768

  • Newbie
  • *
  • Posts: 9
    • View Profile
    • Email
Difference of passing a * parameter and a & parameter
« 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

korczurekk

  • Full Member
  • ***
  • Posts: 150
    • View Profile
    • Email
Re: Difference of passing a * parameter and a & parameter
« Reply #1 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.

enderboy768

  • Newbie
  • *
  • Posts: 9
    • View Profile
    • Email
Re: Difference of passing a * parameter and a & parameter
« Reply #2 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?

eXpl0it3r

  • SFML Team
  • Hero Member
  • *****
  • Posts: 11034
    • View Profile
    • development blog
    • Email
Re: Difference of passing a * parameter and a & parameter
« Reply #3 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.
Official FAQ: https://www.sfml-dev.org/faq.php
Official Discord Server: https://discord.gg/nr4X7Fh
——————————————————————
Dev Blog: https://duerrenberger.dev/blog/

Elias Daler

  • Hero Member
  • *****
  • Posts: 599
    • View Profile
    • Blog
    • Email
Re: Difference of passing a * parameter and a & parameter
« Reply #4 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.
Tomb Painter, Re:creation dev (abandoned, doing other things) | edw.is | @EliasDaler

 

anything