oop - Using a pointer to change an object in C++ -


suppose have multiple text objects of various names , 1 text* called selected_text. text objects hold 1 std::string , have 3 methods: std::string get_text(), void set_text( std::string ) , void append( std::string ). third method appends string std::string , bunch of unrelated stuff.

everytime key pressed, want append character associated key text object selected_text pointing to. after assigning selected_text text object, execute following code:

selected_text->append( key ); 

after code executes, can print value of selected_text->get_text(), appears correct; character associated pressed key appended std::string returned selected_text->get_text(). however, when print value of my_text_object.get_text(), std::string returned appears unchanged; no character appended.

i'm inexperienced pointers , seems fundamental misunderstanding of how work. how can use a text* to change values held within a text?


this might relevant. use following code select text object:

for( auto &text : text_objects ) {     if( text.return_a_boolean_value() )     {         selected_text = &text;     } } 

okay seems helpful, don't know how fix it:

for( auto &text : text_objects ) {     if( text.return_a_boolean_value() )     {         selected_text = &text;         std::cout << selected_text << " " << &text << std::endl;     } }  ...  std::cout << selected_text << " " << &my_text_object << std::endl; 

will give output similar to

0x258d250 0x258d250 0x258d250 0x60a760 

despite fact my_text_object object within text_objects.


solved still confused

so, solved switching type of text_objects std::vector<text> std::vector<text*> , modifying for-each loop. still don't understand why original code didn't work. correct in assuming push_back adds copy of object, or original for-each loop being passed copies?

i used std::vector<text> store text objects. means whenever used push_back add text object array, adding copy of text object, not object itself, vector. code written in question correct. problem is, pointer selected_text modifies copy of each text object (which stored in array), not each object itself.

to fix this, switched std::vector<text> std::vector<text*>, vector of pointers text objects. now, instead of adding copy of each text object when using push_back, add pointer predefined text object. selected_text pointer can used point text* within vector, points corresponding text object.


Comments

Popular posts from this blog

javascript - Bootstrap Popover: iOS Safari strange behaviour -

Magento/PHP - Get phones on all members in a customer group -

session - Logging Out Using PHP -