I have a little problem concerning forward declaration. I have the following class in one file
Robot.h
class Robot
{
public:
void moveForward()
private:
}
With the implementation in Robot.cpp file
And I have a UserReceiver.h class that defines interface for user to interact with the robot etc... This class manages camera with the mouse and I load one instance of the Robot class so that it is possible to interact with it
UserReceiver.h
class Robot;
class UserReceiver
{
public:
void LoadRobot(Robot* _robot) { robot = _robot; }
bool onEvent()
{
etc...
// Calling robot->moveForward() when clicking something
}
private:
Robot* robot;
}
I can give the full code if needed (the 3D engine I am using is Irrlicht). My question is how to forward declare a method associated with the Robot class ? Is there a good design pattern around this question ?
the error i get is (at the line the program is calling robot->moveForward()):
error C2227: left of '->moveForward' must point to class/struct/union/generic type
Thanks a lot for your help
Best regards
You are using Robot
without having a full declaration. Either move the onEvent
implementation into a cpp
file and include the robot.h
header there, or just #include
the robot.h
in userreceiver.h
.
I'd recommend the former.
Sometimes forward declaration is necessary for such mutually referencing classes. However, sometimes complete definition is necessary, for example, visiting class member, or you want to know the size of the class. But at other times, forward declaration is enough.
For class Foo, the following can be forward declaration.
define or declaration Foo*
and Foo&
, including function parameter, return type, local variable, class member variable, and so on.
declaration a function using Foo as a parameter or return type. For instance, Foo bar()
or void bar(Foo f)
. But to invoke the function, definition is required. Because compiler need to use the copy constructor and destructor of function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With