How can I reuse a base class function in a derived class

Say we have these four classes:

  • BinaryTree,
  • SplayTree (which is a subclass of BinaryTree)
  • BinaryNode and
  • SplayNode (which is a subclass of BinaryNode).

In the BinaryTree class, I have these 2 functions, and in SplayTree I would like to reuse it because it works the same way as in SplayTree.

//BinaryTree.cpp bool Find(const T &data) const { Node<T> *found = Find2(data, root); //... } virtual Node<T> * Find2(const T &data, Node<T> *node) const { //... } //SplayTree.cpp using BinaryTree::Find; virtual SplayNode<T> * Find2(const T &data, SplayNode<T> *node) const { //... } 

Now the problem is that when I have an instance of SplayTree and I call Find, instead of SplayTree :: Find2, Binary :: Find2 is called, which I want.

So how can I do this?

EDIT:

Some bugs have been fixed and quetion has been reorganized, I hope that now it will become clear.

+4
source share
2 answers

CRTP idiom is used to solve such problems. Basically, you get a template that receives the derived class as a template parameter, so you can use the type in the return values, etc.

In your case, you need to create a common base template for two tree types and implement Find there, when implementing Find2 in derived classes:

 template <class T> class BaseTree { public: bool Find() { typename T::NodeType* NodePtr = static_cast<T*>(this)->Find2(...); } } template <class T> class BinaryTree<T> : public BaseTree<BinaryTree<T>> { public: typedef Node<T> NodeType; NodeType Find2(); // will be called from BaseTree }; template <class T> class SplayTree : public BaseTree<SplayTree<T>> { typedef SplayNode<T> NodeType; NodeType Find2(); // dito }; 

This basically implements "static polymorphism." The advantage of regular polymorphism is that you can use return types as you would like.

Edit: Added a more detailed description to better match the OP.

+4
source

The problem you are facing is that SplayTree::Find2 not an override of BinaryTree::Find2 , but rather another overload (which hides the original function at the same time). The reason this is another function is because C ++ supports covariant return types, but not arguments for methods, and therefore

At the BinaryTree level BinaryTree call to Find2 takes an argument of type Node<T> , and the only override for this method is BinaryTree::Find2 . If you want the method call to go to the most derived type, you must override the method that provides the method with the same exact signature in the derived class itself.

+2
source

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


All Articles