Thread: Beginners OOP question

  1. #1
    Registered User
    Join Date
    Oct 2006
    Posts
    10

    Unhappy 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

  2. #2
    Code Monkey Davros's Avatar
    Join Date
    Jun 2002
    Posts
    812
    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.
    OS: Windows XP
    Compilers: MinGW (Code::Blocks), BCB 5

    BigAngryDog.com

  3. #3
    Registered User
    Join Date
    Oct 2006
    Posts
    10
    Thank you Davros! That worked perfectly! Many thanks for the assistance,

    Skusey

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. OOP flu
    By Hussain Hani in forum General Discussions
    Replies: 15
    Last Post: 06-27-2009, 02:02 AM
  2. Design layer question
    By mdoland in forum C# Programming
    Replies: 0
    Last Post: 10-19-2007, 04:22 AM
  3. Beginners question
    By jamesstuart in forum C Programming
    Replies: 9
    Last Post: 09-24-2007, 03:24 PM
  4. beginners question: write onto command line
    By xximranxx in forum Windows Programming
    Replies: 7
    Last Post: 05-05-2007, 08:49 AM
  5. Question...
    By TechWins in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 07-28-2003, 09:47 PM