Question

Each of the following statements have include guards around them, for their corresponding header files.

C extends B, things subclass B so they can get a pointer to A– but A has several fields that are subclasses of B.

My current solution is to store Bs in a void array, and use template methods you return the correct object based on run-time type information. But I want to know if there is a way for A to have C fields, even if C needs to link back to A, Ahead Of Time(Compile time).

I have taken a few courses on object oriented programming(they were mostly in java), but none that focused specifically on C++.

This is probably a common problem, and this question has probably already been asked and answered here– but I don't know what keywords to use to find such a solution.

A.h

//#include "C.h" //would cause cyclical include
class A {
public:
    A();
    virtual ~A();

    /**Type must be checked at runtime, because otherwise cyclical includes occur*/
    template <class T> T* getComponent();
private:
    //C* aComponent; //desired implementation
    //Current implementation
    void* components;
    unsigned char componentCount;

};

B.h

#include "A.h"
class B {
public:
    B();
    virtual ~B();
    A* getRoot();

private:
    A* aRoot;
};

C.h

#include "B.h"
class C : B {
public:
    B();
    virtual ~B();
};

Other OOP languages I've used just resolve such problems behind the scenes, where as C++ requires that the build order be correct. I saw several answers to other questions that looked vaguely similar to this one, but they were kind of unclear, please be concise about your answer.

Was it helpful?

Solution

Just use forward declarations:

class C;

Putting that at the top of A.h will allow you to use the class as the type, instead of using void pointers.

EDIT: To clarify, this simply signals to the compiler that there's some class called C, but there's no definition for it. You will be able to declare pointers to it, but you will not be able to use any of its members until the compiler sees the actual definition for it (which shouldn't be a problem).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top