Click to See Complete Forum and Search --> : NullReferenceException (A Noob Question)
Lacrimstein
December 21st, 2006, 10:42 PM
I have a class:
class CNode
{
protected:
...
CNode* m_parent;
public:
...
bool HasParent()
{
return m_parent;
}
}
The method HasParent() is supposed to return false if m_parent = NULL and true otherwise.
Whenever the method HasParent() is called and m_parent = NULL, a NullReferenceException is thrown.
I have already tried using this:
if(!m_parent) return false;
return true;
but everything stayed the same;
What should I do to fix this code? Thank you in advance
cilu
December 22nd, 2006, 03:42 AM
Most likely you are calling HasParent() with a null pointer. Something like this:
CNode* node = NULL;
node->HasParent();
Take a careful look at the exception message to identify the root of the problem. If it doesn't work post the code you are using.
TheCPUWizard
December 22nd, 2006, 06:37 AM
Cilu is probably correct. Use a debugger!
Lacrimstein
December 22nd, 2006, 07:15 PM
OK, I have completely rewritten the whole class, and I still have the same error. Here's the full source code:
class CNode
{
public:
CNode* m_parent;
CNode* m_child;
CNode* m_next;
CNode* m_previous;
CNode()
{
m_parent = NULL;
m_child = NULL;
m_next = NULL;
m_previous = NULL;
}
CNode(CNode* parent)
{
CNode();
AttachTo(parent);
}
void AttachTo(CNode* parent)
{
if(parent)
{
if(parent->m_child)
{
CNode* node = parent->m_child;
while(node->m_next != NULL) node = node->m_next;
node->m_next = this;
m_previous = node;
}
else
{
parent->m_child = this;
}
}
m_parent = parent;
}
};
int main()
{
CNode n1(NULL);
CNode n2(&n1);
CNode n3(&n1);
CNode n4(&n1);
CNode n5(&n3);
CNode n6(&n3);
return 0;
}
I tried using the debugger. The problem is with the line
while(node->m_next != NULL) node = node->m_next;
in AttachTo(), when creating n2. It appears as though the condition in the loop is being completely ignored... Any ideas what might I be doing wrong???
Lacrimstein
December 23rd, 2006, 04:08 PM
I found the error:
the call to CNode() was for some reason ignored in CNode(CNode* parent) and all the pointers were initialized to random addresses.
TheCPUWizard
December 23rd, 2006, 05:31 PM
Calling one constructor from another???? :mad: :mad:
Move the logic to another function..
codeguru.com
Copyright WebMediaBrands Inc., All Rights Reserved.