C++ Compilation error: Undefined identifier (for a function parameter)

2.4k Views Asked by At

I have a C++ class main.cpp in which I created a class like following:

class MapSearchNode
{
 public:
unsigned int x;  // the (x,y) positions of the node
unsigned int y; 

MapSearchNode() { x = y = 0; }
MapSearchNode( unsigned int px, unsigned int py ) { x=px; y=py; }

float goalDistance( MapSearchNode &nodeGoal );

};
float MapSearchNode::goalDistance( MapSearchNode &nodeGoal )
{
float xd = fabs(float(((float)x - (float)nodeGoal.x)));
float yd = fabs(float(((float)y - (float)nodeGoal.y)));

return xd + yd;
}

int main{
    //treatment
}

And it works fine but then I wanted to seperate the class MyClass, so I created a MyClass.h and MyClass.cpp and seperated the code like following:

MyClass.h

#ifndef _MAPSEARCHNODE_H
#define _MAPSEARCHNODE_H


class MapSearchNode
{
public:
    MapSearchNode();
MapSearchNode( unsigned int px, unsigned int py );

public:
unsigned int x;  
unsigned int y; 
    float goalDistance( MapSearchNode &goalNode );

};
#endif

MyClass.cpp

#include "MapSearchNode.h"

MapSearchNode::MapSearchNode():x(0), y(0))
{}
MapSearchNode::MapSearchNode( unsigned int px, unsigned int py ):x(px), y(py) 
{}

float MapSearchNode::goalDistance(MapSearchNode &goalNode ){
float xDistance = fabs(float(((float)x - (float)goalNode.x)));
float yDistance = fabs(float(((float)y - (float)goalNode.y)));

return xDistance + yDistance;
}

Bur when i try to compile i have an error:

Undefined identifier goalNode; 
 //for the function goalDistance

Can someone please explain me why am I getting this error and how to fix it.

EDIT: I hope I haven't forgotten anything now.

EDIT: Well thanks a lot to those who downrated. Some of us are not experts like you and it's hard for them to see errors even small ones!

1

There are 1 best solutions below

2
On

On the first look there are 2 possible reasons for this error:

The most obvious one: Your class definition is incomplete, it should be

class MyClass
{
public:
    unsigned int x; 
    unsigned int y; 

    MyClass() { x = y = 0; }
    MyClass( unsigned int px, unsigned int py ) { x=px; y=py; }

    float Calculate( MyClass &myClass );
}; // semicolon

float MyClass::Calculate( MyClass &myClass )
{
     if(x<myClass.x)
             ....//treatment
}

Additionally, make sure your source file (.cpp) includes your header file (.h)

So both files would look like that:

// .h file
class MyClass
{
public:
    unsigned int x; 
    unsigned int y; 

    MyClass() { x = y = 0; }
    MyClass( unsigned int px, unsigned int py ) { x=px; y=py; }

    float Calculate( MyClass &myClass );
};

// .cpp file
#include "MyClass.h"
//definition of constructors
float MyClass::Calculate( MyClass &myClass )
{
   if(x<myClass.x)
             ....//treatment

}