Question

I'm having trouble understanding when/if single/multiple inheritance should be used vs forward declaration & I'd like to get a better understanding of it in the following example. If someone could point me in the right direction, or explain differences between them, it would be much appreciatd.

Following is sample of data structure I'm dealing with;

There exists 1 Parent, 1 SubParent & many different Children types. ie there's many Children per SubParent per Parent. Some Children need access to other Children objects. Children will use similar functions to each other ie ParseSelf/Display/Save/Edit. If Children get changed (ie Edit/Save), also need to update data in SubParent, Parent & possibly other Children.

I'm wanting to know what would be best way to implement something like this? I've come up with two alternatives below. If more clarification/information is needed please let me know.

class SubParent;
class Children;

class Parent
{
    ...
    int iParent;
    SubParent *pSubParent;
};

class SubParent
{
    ...
    int iSubParent;
    std::list<Children> childrenList;
};

class Children
{
    ...
    int iChild;
    int ChildType;
    char *pData;
};

versus;

class Parent
{
    ...
    int iParent;
};

class SubParent : public Parent
{
    ...
    int iSubParent;
};

class Children : public SubParent
{
    ...
    int iChild;
    int ChildType;
    char *pData;
};

Thank you.

EDIT: Main job of Parent; maintains information about file ie location of SubParent, SubParent size, total size of all data including self. Main job of SubParent; contains information about Children ie size & location of Children. Both Parent/SubParent don't really do much else except keep these items upto date.

Was it helpful?

Solution

I would recommend going with the first approach, with the following changes:

  1. Add a member in SubParent that points to the Parent. This will allow you traverse the objects both ways.

    class SubParent
    {
        ...
        int iSubParent;
        Parent* parent;
        std::list<Children> childrenList;
    };
    
  2. You should keep a list of Children* in SubParent instead of a list of Chilren if you are going to have different types of Children. If Children will never have any sub-classes, having a list of Children is good enough.

  3. Add a pointer to the SubParent in Children. Again, that will allow you to traverse the objects both ways. Given a Children, you would be able to access its siblings through that pointer.

    class Children
    {
        ...
        int iChild;
        int ChildType;
        SubParent* subParent;
        char *pData;
    };
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top