I'm heading into my second CS course this semester. It's going to cover OOP using C++. Now I know OOP rather well through teaching myself Obj-C and Cocoa, but I'm trying to get myself familiarized with C++ before the start of the semester. I decided to build an app using Objective-C++, incorporating a Cocoa/Obj-C view and C++ model. I started to get some odd output in the console window. I then created a stripped down C++ console version of the app and had the same problems. If only happens when I have an object return the pointer of another object.
When the function is called, object2 is created on the stack. You then keep a pointer to it. However, when the function returns, the stack unwinds and object2 is destroyed. At that point the pointer is directed at garbage.
Please post your well indented code in [code][/code] bbcode tags.
At a glance, one possible problem is that you are assigning the address of a local variable to a member variable in the ObjectOne constructor. This local variable is destroyed at the end of the function, upon which the member pointer points to a destroyed object. Do you even need a pointer in the first place?
There are several possible solutions to this issue. I'll attempt to lay out the pros and cons of a few.
1) Make object2 a class member of ObjectOne to begin with, rather than making the pointer a member. This is fine for the most part, and probably the easiest solution to the issue. The downside is that it requires ObjectTwo.h to be #included in ObjectOne.h----you can't use a forward-declare. However, here you're doing that anyway.
2) Allocate object2 on the heap using new and assign it to the pointer. The downside here is that you are required to write a destructor now to free that memory, and also a copy constructor and assignment operator (or disable those operations by making them private). Classes written this way tend to get unwieldy very fast, I don't recommend it.
3) Do the same as (2), but use a std::tr1::shared_ptr<ObjectTwo> rather than an ObjectTwo*. Then all copying and destruction will be handled automatically. This option should be preferred to (1) only if there's some reason you need the class member to be a pointer----say, for polymorphism or to enable a forward-declaration to break an include cycle.
The lesson here: Don't overuse pointers. And when you do use them, consider using a smart pointer rather than a "bare" pointer. It will make your life easier.