简体   繁体   中英

C++ setting attribute of a derived class to an unknown class object, derived from same base class?

I have 3 classes, a Base class, a Parent class and a Child class. Parent has m_children vector which can have multiple children in it, but a child can only have one parent object as it's m_parent attribute. How should I implement this? Here's a quick preview of the classes (rewritten for the sake of the question)

Base.h

class Base
{
public:
    Base();
    virtual void getClid();
    virtual void setClid();
private:
    int m_clid;
};

Parent.h

#include <vector>
#include "Base.h"
#include "Child.h"

class Parent : public Base
{
public:
    Parent();
    void addChild(Child* child);
    void removeChild(Child* child);
    Child* getChild(int index);
private:
    std::vector<Child*> m_children;
};

Child.h

#include "Base.h"

class Child : public Base
{
public:
    Child();
    Base* getParent();
    void setParent(Base* parent);
private:
    Base* m_parent;
};

Now the problem here, as you see, is that I can only include "Parent.h" in "Child.h" OR the other way around, not both. How do I tell Child the type of his parent? Code below works fine, but if I want to call m_parent->removeChild(this); for example from Child object's destructor, it won't work cause Child only knows getClid and setClid methods of Parent, which are both defined in "Base.h"

If I understand well your question, you can do something like that for Child.h:

#include "Base.h"

class ParentObject;

class Child : public Base
{
public:
    Child();
    ParentObject* getParent();
    void setParent(ParentObject* parent);
private:
    ParentObject* m_parent;
};

You can forward-declare child in the Parent header and vice versa, breaking the circular dependency.

#include <vector>
#include "Base.h"

class Child;    
class Parent : public Base
{
public:
    Parent();
    void addChild(Child* child);
    void removeChild(Child* child);
    Child* getChild(int index);
private:
    std::vector<Child*> m_children;
};

and

#include "Base.h"
class Parent;    
class Child : public Base
{
public:
    Child();
    Parent* getParent();
    void setParent(Parent* parent);
private:
    Parent* m_parent;
};

But I gotta say, there are way too many raw pointers and too many setters and non-interfaces here. I'm smelling a dodgy design.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM