Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Forward declaration of a method

I have a little problem concerning forward declaration. I have the following class in one file


class Robot
   void moveForward()

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


class Robot;
class UserReceiver
     void LoadRobot(Robot* _robot) { robot = _robot; }

     bool onEvent()
         // Calling robot->moveForward() when clicking something
 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

like image 404
Vincent Avatar asked Mar 25 '23 06:03


2 Answers

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.

like image 184
Peter Wood Avatar answered Apr 02 '23 06:04

Peter Wood

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.

like image 42
Scy Avatar answered Apr 02 '23 05:04