Circular Dependence in case of inherithed class with override methods

Viewed 90

I have the following situation :

class GenericObject{
virtual Attribute* getAttribute(){..}
}

class PlaneObject : public GenericObject{
Attribute1* getAttribute()override{..}
}

-----------------------------------------block1

class Attribute{
virtual GenericObject* getObject(){..}
}

class Attribute1 : public Attribute{
PlaneObject* getObject()override{..}
}

----------------------------------------block2

Since i'm overriding the getAttribute() methods in PlaneObject, changing its return type from Attribute* to Attribute1* , this is only allowed if the compiler is aware that Attribute1 is derived from Attribute.

Then I should put block2 before block1.

However, block2 also needs to know that PlaneObject is derived from GenericObject, in order to compile, because of the overridden methods in Attribute1 class.

I don't know if it is just bad design pattern or what. I've been looking for similar questions but didn't find the exact same picture i'm facing.

1 Answers

there is no simple solution. you can try to break the cycle this way:

// GenericObject.h
class Attribute;
class GenericObject{
virtual Attribute* getAttribute();
};

// Attribute.h
class GenericObject;
class Attribute{
virtual GenericObject* getObject();
};

// PlaneObject.h
#include "GenericObject.h"
class Attribute1;
class PlaneObject : public GenericObject
{
Attribute* getAttribute()override;
Attribute1* getAttributeRealType();
};

// Attribute1.h
#include "Attribute.h"
class PlaneObject;
class Attribute1 : public Attribute{
GenericObject* getObject()override;
PlaneObject* getObjectRealType();
};

// implementation example
// PlaneObject.cpp
#include "PlaneObject.h"
#include "Attrubute1.h"
Attribute* PlaneObject::getAttribute()
{
    return getAttributeRealType();
}
Attribute1* PlaneObject::getAttributeRealType()
{
    return new Attribute1;
}
// attribute1.cpp
#include "Attribute1.h"
#include "PlaneObject.h"
GenericObject* Attribute1::getObject()
{
   return getObjectRealType();
}
PlaneObject* Attribute1::getObjectRealType()
{
   return new PlaneObject;
}
Related