-
Beginners OOP question
Hi,
When using classes in C++, how can you have it where both classes have a reference to each other? For example, we have a space ship class, and a space ship's component class:
Space ship components header...
Code:
#include "Ship.h"
class ShipComponent
{
public:
/* blah */
protected:
Ship* mMyShip; // Reference to its ship so it can do stuff to it
};
Space ships header...
Code:
#include "ShipComponent.h"
#include <vector>
class Ship
{
public:
private:
// List of components the ship has
vector<ShipComponent*> mShipComponents;
};
Now obivously the compiler has trouble sorting this out, so is this just poor design on my behalf, or are there ways round this problem? Any help will be greatly appreciated,
Skusey
-
You are creating a circular reference and you need a technique called "forward declaration" to avoid it. That is to declare a class name, rather than include it so as not to create a circular reference.
Like this:
Code:
// REMOVED: #include "Ship.h"
// Forward Declaration
class Ship;
class ShipComponent
{
public:
/* blah */
protected:
Ship* mMyShip; // Reference to its ship so it can do stuff to it
};
In "ShipComponent.cpp" you can include "Ship.h" if you need to call methods on the Ship object.
-
Thank you Davros! That worked perfectly! Many thanks for the assistance,
Skusey