Jump to content
  • Advertisement
Sign in to follow this  
comfortablynumb84

Quick question

This topic is 4258 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

Hi again! I need to know why this function returns a reference (being "boss" a class ): Boss & operator=( const Boss & b ); Why is this function returning a reference? shouldn't it return a copy of the object? for example if you do this assignament: Boss boss1; Boss boss2; boss2 = boss1; Then "boss2" shouldn't be a new object with members copied from boss1? and not a reference. Thanks in advance.

Share this post


Link to post
Share on other sites
Advertisement
The reference is returned from the expression, not to the first object. In your example, nothing called the assignment, so it disappears.

eg.

2 + 2;

The addition operator returns an int, with the value 4, but in that example, nothing is using it, so it disappears and nothing happens.

a = b;

The assignment operator returns a const reference to 'a', but in this example, nothing uses that reference, so that also disappears. The value of 'a' changes within the operator function, but that's a different issue. :)

Share this post


Link to post
Share on other sites
Quote:
Original post by comfortablynumb84
Hi again! I need to know why this function returns a reference (being "boss" a class ):

Boss & operator=( const Boss & b );

Why is this function returning a reference? shouldn't it return a copy of the object? for example if you do this assignament:

Boss boss1;
Boss boss2;
boss2 = boss1;

Then "boss2" shouldn't be a new object with members copied from boss1? and not a reference.

Thanks in advance.


No. 'boss2' is *already* an object *before* you do the assignment. The assignment *changes the current state* of 'boss2'; there is no object that needs to be created. The reference that is returned is to boss2. That is done so that you can chain assignments: e.g. 'boss1 = boss2 = boss3'.

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!