Jump to content
  • Advertisement
Sign in to follow this  
xegoth

Simple function question

This topic is 5469 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

What's the syntax for passing a class to a function so that its values can be modified? Is it void function(MYCLASS* myclass) { } then to call it.. function(&someclass); All the times I've passed classes before I wasn't changing any of their values.

Share this post


Link to post
Share on other sites
Advertisement
You can pass it by pointer or by reference. In both cases you can modify the members of the class.

void f(MyClass& c) //by reference
void f(MyClass* c) //by pointer

Share this post


Link to post
Share on other sites
Quote:
Original post by xegoth
All the times I've passed classes before I wasn't changing any of their values.


That is most likely because you were 'passing by value". Use a pointer or a reference like Washu posted.

Share this post


Link to post
Share on other sites
Well the prefered way is using references like so:

void function(MYCLASS& myclass) {}

Which you use it like this:

function(someclass);

But using a pointer should work fine too. I can't see anything wrong with the example you've posted. Try posting the actual code you're having trouble with.

Share this post


Link to post
Share on other sites
Passing by reference doesn't make it obvious to calling code that you might be modifying the value. If this bothers you then a guideline to follow is:

If you don't need to modify the object pass it by constant reference.
If you do need to modify it pass it by pointer.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!