C++ pass by reference local variable -


i'm new c++

i have following class:

class user { public:     user(const string& username) {          m_username = username;     }      string username() const {         return m_username;     }      void setusername(const string &username) {         m_username = username;     }  private:     string m_username; }; 

here main.cpp code

user *createuser() {     string username = "someuser";     user *u = new user(username);     return u; }  int main(int argc, char *argv[]) {     user *u2 = createuser();     cout << u2->username() << endl;     return 0; } 

in function createuser() i'm creating local variable username , pass reference user class constructor. when function ends, variable username goes out of scope, therefore value of m_username member of class user should deleted.

but still accessible outside of function, e.g. main method prints "someuser" console.

why?

when function ends, variable username goes out of scope, therefore value of m_username member of class user should deleted.

that's not right. don't see implementation of user constructor, guess copy of given string. m_username has no further link local variable, it's own instance.


Comments

Popular posts from this blog

Delphi XE2 Indy10 udp client-server interchange using SendBuffer-ReceiveBuffer -

Qt ActiveX WMI QAxBase::dynamicCallHelper: ItemIndex(int): No such property in -

Enable autocomplete or intellisense in Atom editor for PHP -