Is multiple inheritance acceptable for nodes in a tree?

It was interesting to me:

With a tree, a root can have several children and without id. All nodes (except the root) have an identifier, and leaf nodes cannot have children. Fixed which type should be used for each depth. Thus, the leaves are always of the same type, as well as the parents of the leaves.

Since the root and nodes can have children, and only nodes have an identifier, I was wondering if the following use of multiple inheritance is acceptable:

class NodeWithId
{
    private:
        std::string m_id;
};

template<typename T>
class NodeWithChildren
{
    private:
        std::vector<T> m_nodes;
};

class Network: public NodeWithChildren<Subnet>
{
};

class Subnet: public NodeWithChildren<Machine>, 
                     public NodeWithId
{
};

class Machine: public NodeWithChildren<Application>, 
               public NodeWithId
{
};

class Application: public NodeWithId
{
};

Or is there a better way to implement this?

edit:

  • removed virtual
  • class name changed
+3
source share
4 answers

Or is there a better way to implement this?

IMHO, , . Level1 2.

. , - , Node Node ( ).

+2

:

class NodeWithId
{
    private:
        std::string m_id;
};

template<typename T>
class NodeWithChildren : public NodeWithId
{
    private:
        std::vector<T> m_nodes;
};

class Root: public NodeWithChildren<Level1Node>
{
};

class Level1Node: public NodeWithChildren<Level2Node>
{
};

class Level2Node: public NodeWithChildren<LeafNode>
{
};

class LeafNode: public NodeWithId
{
};

, NodeWithChildren, . NodeWithChildren NodeWithId, NodeWithChildren NodeWithId .

, "" ...

+2

, , , , '

, -, , ? , .

, ?

+1

, .

, , node.

. , - .

, , ? , . , . , , .

If this has added any benefit, then it may be worth what is needed for some purposes, but it is really the opposite of what you want from a structure, such as a tree, that should be as easy to use and understand as possible and have several memory allocations as much as possible and ideally good performance.

-1
source

Source: https://habr.com/ru/post/1732332/


All Articles