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
Post a Comment