Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to derive from/extend a recursive class
    primarykey
    data
    text
    <p>I have a recursive class, a kind of tree, that has instances of itself as member variables. For example:</p> <pre><code>template&lt;class T&gt; class Tree { public: /* Constructors, etc. */ protected: T m_value; Tree&lt;T&gt; *leftChild; Tree&lt;T&gt; *rightChild; }; </code></pre> <p>If I want to add a method that prints all the values using an in-order traversal, I could do this:</p> <pre><code>template &lt;class T&gt; void Tree&lt;T&gt;::printInOrder() { leftChild-&gt;printInOrder(); std::cout &lt;&lt; m_value &lt;&lt; std::endl; rightChild-&gt;printInOrder(); } </code></pre> <p>But what if, for various reasons, I couldn't or didn't want to change Tree's implementation? If the class wasn't recursive, i.e. didn't contain instances of itself, I could just derive from Tree and implement a new method in the derived class. But this approach doesn't work for Tree.</p> <pre><code>template &lt;class T&gt; class DerivedClass : public Tree&lt;T&gt; { public: void printInOrder(); } template &lt;class T&gt; void DerivedClass&lt;T&gt;:: printInOrder() { this-&gt;leftChild-&gt;printInOrder(); std::cout &lt;&lt; this-&gt;m_value &lt;&lt; std::endl; this-&gt;rightChild-&gt;printInOrder(); } </code></pre> <p>leftChild and rightChild are instances of Tree and thus don't have a printInOrder() method. </p> <p>Can anyone suggest a way to do this in a modular way without changing Tree's implementation. It's ok to change how it is implemented in general, as long as you don't have to change it whenever you want to extend/derive from the class. I can see a possible way to do it by making the template class T have methods to do the things I want, but that just seems ugly. There must be a better way.</p> <p>I'm perfectly happy for someone to point out how I've overlooked something obvious. It certainly feels like I have.</p> <p><strong>Edit:</strong> The point is not how to implement printInOrder(). That was just an example. The point is how to derive a class so that the children are also the derived class.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload