Basic Pointer Help
I'm having a problem in some code and I think it's because I've misunderstood how pointers are supposed to work. I've read the tutorials but perhaps I haven't understood them correctly. My aim is to post some code, explain what I think is supposed to happen and then maybe one of you lovely people could explain why it does not?
Just to say that this is pseudo code to try and demonosrate the point. You can presume that AddOne actually adds one to count and vector is a correct lvalue and the like.
//this should point bar to the rvalue of foo?
MyClass *bar = &foo;
//this vector now holds the object foo
//this should add 1 to count inside foo because above I declared bar as a pointer to foo. The operations that I perform on bar should be done on foo as I told bar to point to the addressof foo
for(int i = 0; i < vector.size(); i++)
//I want this to call foo.GetCount which was updated by bar.AddOne()
Does foo being inside a data structure matter to bar->AddOne()? More likely, have I got the wrong idea here?
Thanks in advance.
You should post something that will compile, not random 1-line snippets of all your ideas.
Each line you post is fine (in a context we assume), but that's not the same as the context in which you tried it (or understood it).
Your theory is correct, but I don't believe it will work. I cannot say for sure since you have not provided the declaration for your vector, though.
Remember that if you declare your vector as
Then, a copy of foo will be made and inserted into vector. Therefore, your action on bar (or foo) won't affect the object inside the vector.
You would need a pointer to be stored inside the vector for it to work properly.
(See smart pointers if you need to use pointers.)