0

I've never used or needed inheritance for any of the code I have written. My understanding of best practices is that inheritance is rarely used/needed in most coding applications. I have come across a use-case where I think inheritance might make sense, and I'm wanting help evaluating if this is a correct place to use inheritance.

I'm storing each node of the branch and bound algorithm as an object. The root node is constructed using one algorithm, and left and right nodes are constructed from the previous node using a different algorithm.

    class Node {
    public:
        int bound();
        Node left();
        Node right();
        Node() = delete;
        // more stuff
    };
    class Root : public Node {
        Root(T m);
        // maybe more stuff, maybe not
    };

In this case, the Root node isn't very special. The only reason to define it is to make it clear that most Nodes aren't constructed from Ts. Writing the code is not easier with inheritance.

Is this an appropriate place to use inheritance? What other considerations should I make before using inheritance here?

mana
  • 545
  • 4
  • 12
  • The trouble with *polymorphic* (!) inheritance is that you almost invariably run into cache-locality problems as you have to allocate separate objects individually. Inheritance as a means of composition, however, is immensely useful. Perhaps clarify in your question which of these you are referring to. – bitmask Aug 13 '20 at 22:31
  • @bitmask "you have to allocate separate objects individually" I don't know what this means. If your question is whether or not I will use virtual functions or any kind of RTTI, no I don't plan to use those. – mana Aug 13 '20 at 22:35
  • In that case, the only "problem" with inheritance is slicing, which can be avoided by using private or protected inheritance. Otherwise I'm not sure what you're asking. – bitmask Aug 13 '20 at 22:38
  • What is the difference between constructing `Root` and `Nodes`? Different values are set? – Louis Go Aug 14 '20 at 01:13
  • @LouisGo Nodes only come from nodes. Roots come from Ts. The constructor for Nodes and Roots are different and complicated (both are ~O(n^3) complexity). The actual data members they store will be the same, although Roots will satisfy an extra invariant by virtue of being a Root. – mana Aug 14 '20 at 01:22
  • 1
    @mana: You want a factory method, then. So `Node Node::mkRoot(T m)` will construct a root node while either `Node::Node(Stuff)` or `Node Node::mkTreeNode(Stuff)` will construct a non-root (i.e. tree node). – bitmask Aug 14 '20 at 01:30
  • Is knowing the `Node` is `Root` important? Or just creation strategy is important? If you treat `Node` and `Root` the same after creation, I'll suggest don't use inheritance. – Louis Go Aug 14 '20 at 01:34

0 Answers0