C++ object life scope -


i seem have misinterpreted life scope of objects in c++. if you'd consider following:

class myclass{ public:     int classvalue;     myclass(int value){         classvalue = value;     }     static myclass getmyclass(int value){         myclass m1 = myclass(value);         return m1;     } };  int main() {     myclass m1 = myclass(3);      cout << m1.classvalue << endl;     m1 = myclass::getmyclass(4);     cout << m1.classvalue << endl;          return 0; } 

this outputs:

3 4 

and thought, when m1 gets non-dynamic object, has been created 'on stack' of getmyclass function, me trying value wouldn't work, because object dead. enlighten me? not spare me details!

and thought, when m1 gets non-dynamic object, has been created 'on stack' of getmyclass function, me trying value wouldn't work, because object dead. enlighten me? not spare me details!

there bit of misunderstanding.

yes, object created on stack in getmyclass.
yes, object dead when function returns.

however, line:

m1 = myclass::getmyclass(4); 

assigns return value of function m1 before object dead. object lives long enough allow run time complete assignment.

btw, line

myclass m1; 

is not right since myclass not have default constructor. can replace lines

myclass m1; m1.value = 3; 

by 1 liner

myclass m1(3); 

update

you need change constructor of myclass.

myclass(int value){     value = value; // not initialize                    // member variable of class.                    // argument shadows member variable. } 

use:

myclass(int valuein) : value(valuein) {} 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

android - Keyboard hides my half of edit-text and button below it even in scroll view -

css - Make div keyboard-scrollable in jQuery Mobile? -