Simple function question

Started by
4 comments, last by krez 19 years, 6 months ago
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.
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 referencevoid f(MyClass* c) //by pointer

In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.

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.
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 a function takes a non-const reference, you ought to know that it might be changed.
--- krez ([email="krez_AT_optonline_DOT_net"]krez_AT_optonline_DOT_net[/email])

This topic is closed to new replies.

Advertisement