#include <iostream>
using namespace std;
class Object{};
class Connection
{
public:
Connection(Object * _obj);
Object * obj;
void status();
};
Connection::Connection(Object * _obj)
{
obj = _obj;
}
void Connection::status()
{
cout << obj << endl;
}
int main() {
Object * myObj = new Object();
Connection * myConn = new Connection(myObj);
delete myObj;
myObj = NULL;
cout << myObj << endl;
myConn->status();
/*
Output is:
0
0x25ec010
but should be:
0
0
*/
}
I thought I am only working with pointers in this example. So I don’t understand why the pointer in “myConn” is not set to NULL too, because there are two pointers which point to the same address.
It shouldn’t be 0 because you are copying pointer value. Try using references (&) instead.
Maybe this is not a best example, and
boost::shared_ptrwill be better solution, but this code will work: