Simple function question
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.
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 referencevoid f(MyClass* c) //by pointer
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.
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.
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.
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.
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.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement