Archived

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

Scope

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

This is a very dumb question, but how do you return a custom class without local scope (I don''t even think I said that right)? Lemme show you:
  
CCustomClass ReturnCustomClass(void)
{
     CCustomClass cClass;
     ....
     
     return (cClass);
}
  
Wouldn''t this ''return the address of a local variable''? How would I prevent it?

Share this post


Link to post
Share on other sites
No, since the return-type is a value-type it will not return an address to cClass, instead an anonymous variable is created on the stack whenever you call ReturnCustomClass, and when the function returns cClass is copied into that anonymous variable. Therefore it can be expensive to call ReturnCustomClass if CCustomClass is large.

  
CCustomClass ReturnCustomClass(void) // return by value

{
CCustomClass cClass;
return (cClass); // cClass is copied into a ''return variable''

}

CCustomClass & ReturnCustomClass2(void) // return by reference

{
CCustomClass cClass;
return cClass; // here the address of cClass is returned (not good)

}

CCustomClass * ReturnCustomClass3(void) // return a pointer

{
CCustomClass cClass;
return &cClass; // here too, the address of cClass is returned

}

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Something the last poster didn''t mention is the last two examples he gave won''t work. aClass is declared as a local variable but when it goes out of scope a reference to it or a pointer to it is not well-defined and any use of the return value will make your program to kaput.

Share this post


Link to post
Share on other sites