Skip to main content
GameDev.net gamedev.net
🔒 Locked

Scope

Started by masonium Oct 23, 2001 at 6:38 PM 2 replies 300+ views
Original Post
masonium
masonium
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?
Dactylos
Dactylos
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

}

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.