I have a Node class and a NodeManager class. NodeManager objects hold a pointer to Node. I want this Node pointer to point to a Node object that is allocated on the heap. The heap allocation happens in NodeManager.init()
.
Here's the code.
class Node
{
public:
int index;
};
class NodeManager
{
public:
NodeManager() {}
void initNode(Node *b)
{
b = new Node();
}
Node *node;
};
int main()
{
NodeManager manager;
manager.initNode(manager.node);
cout << manager.node << endl; //prints a bad pointer
system("pause");
return 0;
}
Of course, when I change initNode()
to:
void initNode()
{
this->node = new Node();
}
the manager
object actually "remembers" its node
's address.
The problem is that in the first code, the address isn't remembered and the application prints out a bad address. Why is that?
Edit: To make things clearer, I'm working with a class that has a data member that is a pointer to an object. My class has a recursive member function that takes its data member pointer as a "starting point" parameter and keeps calling itself to allocate and create the object's "children" too. But then, I get this problem. the private data member isn't remembered and turns out to be NULL or a bad pointer after all.
The problem is that you are trying to change the value of the pointer but you are passing it by value. As a consequence, it is the copy that is changed inside your function.
Pass by value creates a copy of the object passed to the function and any changes to it made within the function are only made to the copy. Pass the pointer by reference instead if you want to change the pointer with the function. Something like
void initNode(Node* &b)
{
b = new Node();
}