Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Circular Dependence in case of inherithed class with override methods

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.

like image 209
Andrea Loforte Avatar asked Nov 21 '25 15:11

Andrea Loforte


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;
}
like image 174
Alexander Avatar answered Nov 24 '25 05:11

Alexander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!