Archived

This topic is now archived and is closed to further replies.

Tai-Pan

little doubt about references and default values

Recommended Posts

I have a little and stupid C++ doubt. Suppose I have this method: Void SetScore(const int &newscore=10) { score=newscore; } Well my problem is , im not sure if I can use the default value and use it to set my score, since im passing a reference (an address). Can anyone help me here? Thanks

Share this post


Link to post
Share on other sites
quote:
Original post by Tai-Pan
Well my problem is , im not sure if I can use the default value and use it to set my score

Yes you can. You are referencing a static constant using a const reference, which is entirely acceptable. If the parameter were a non-const reference to int, then you could not bind it to "10", since you are able to modify values through non-const references, while "10" is a non-modifiable value.

Share this post


Link to post
Share on other sites
You''re passing a reference, which IS a pointer, but is
treated as a standard variable.

--
MFC is sorta like the swedish police... It''''s full of crap, and nothing can communicate with anything else.

Share this post


Link to post
Share on other sites
What happens when you call SetScore() is that the compiler will create a temporary variable, assign the value of 10 to the variable and pass the address of the variable to the SetScore() function, where it will de-reference the address and assign it to score.

Which doesn''t save you any memory, and in this case actually causes you to use more memory. In general, constant primitive arithmetic values should be passed by value, not by reference.

Share this post


Link to post
Share on other sites
You can pass structs and classes by reference instead of passing a pointer. It (IMO) produces easier to read code than passing pointers. If you write

void some_method( SomeClass& c ) 


you can access methods and member variables vith the normal "." operator instead of using the explicit dereferencing operator "->" you''d have to use if you wrote

void some_method( SomeClass* c ) 


Basically, anything more complex than the primitives (char, int, float, double, bool, ...) makes sense to be passed as reference.

Share this post


Link to post
Share on other sites