Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ "Incomplete type not allowed" error accessing class reference information (Circular dependency with forward declaration)

Had some issues in my code recently surrounding what I now know of as a Circular dependency. In short there are two classes, Player and Ball, which both need to use information from the other. Both at some point in the code will be passed a reference of the other (from another class that will include both .h files).

After reading up on it, I removed the #include.h files from each one and went with forward declaration. This solved the issue of being able to declare the classes in eachother, but I'm now left with an "Incomplete type error" when trying to access a passed reference to the object. There seem to be a few similar examples around, though often mixed with more complex code and hard to narrow down to the basics.

I've rewritten the code in it's simplest form (a skeleton essentially).

Ball.h:

class Player;  class Ball { public:     Player& PlayerB;     float ballPosX = 800; private:  }; 

Player.h:

class Ball;  class Player { public:     void doSomething(Ball& ball); private: }; 

Player.cpp:

#include "Player.h"  void Player::doSomething(Ball& ball) {     ball.ballPosX += 10;                   // incomplete type error occurs here. } 

Any help understanding why this is the case would be greatly appreciated :)

like image 752
nat1707828 Avatar asked Feb 13 '14 01:02

nat1707828


2 Answers

If you will place your definitions in this order then the code will be compiled

class Ball;  class Player { public:     void doSomething(Ball& ball); private: };  class Ball { public:     Player& PlayerB;     float ballPosX = 800; private:  };  void Player::doSomething(Ball& ball) {     ball.ballPosX += 10;                   // incomplete type error occurs here. }  int main() { } 

The definition of function doSomething requires the complete definition of class Ball because it access its data member.

In your code example module Player.cpp has no access to the definition of class Ball so the compiler issues an error.

like image 173
Vlad from Moscow Avatar answered Sep 23 '22 13:09

Vlad from Moscow


Player.cpp require the definition of Ball class. So simply add #include "Ball.h"

Player.cpp:

#include "Player.h" #include "Ball.h"  void Player::doSomething(Ball& ball) {     ball.ballPosX += 10;                   // incomplete type error occurs here. } 
like image 24
Nima Soroush Avatar answered Sep 24 '22 13:09

Nima Soroush