I've created two separate binary tree classes, with some shared functions/variables and some that are not shared. So I have tried to abstract away the similarities in a base BinaryTree class.
class BinaryTree{
public:
BinaryTree(std::vector<int> &vec);
BinaryTree *left;
BinaryTree *right;
std::vector<int> dataVector;
//functions...
}
The derived classes share the type of data with the base class (dataVector). But they require the creation of new nodes of their derived type.
class Derived : public BinaryTree{
public:
void function(){
left = new BinaryTree();
};
Obviously by creating a new BinaryTree, we lose the extended functionality of the Derived class, but if I were to declare left and right as Derived* inside the Derived class, I would defeat the whole purpose of abstraction in the first place.
How would I go about implementing this if it's even possible?
EDIT: one of the derived classes might implement quick sort
class QuickSort : public BinaryTree{
public:
//chooses whether to sort itself or the children nodes recursively
void sortVector(){
if(isSorting) partition(),
else if (left->isSorting || left->areNodesSorting) left->sortVector();
else if(right->isSorting || right->areNodesSorting) right->sortVector();
}
void partition(){ /* partition implementation */};
void setupNodes(){
/* choose where to split dataVector depending on the pivot, and initialize
the pointers - left = new QuickSort(chosenVector); etc*/ };
bool isSorting = true, isLeaf = true, areNodesInit = false, areNodesSorting =
false;
int pivotIndex, j = 0, i = -1;
int pivotValue;
}
There are obviously other helper functions. And I need step by step sorting, so I've put all the variables as instance variables - should they be part of Payload? Also as you can see some functions use recursion and need to know of all the different children nodes as well.
BinaryTreeclass which represents a node, and functions that operate on nodes. You can put those functions anywhere you want; inheritance is not required. Ask yourself: what IS A relationship are you modelling here?BinaryTreeis supposed to abstract away the similarities to avoid duplicate code. If there's a better way to achieve it, I'm all earsfunctioncan't apply to allBinaryTrees, I think it would make the question better if you show an example of what "extended functionality" you're trying to achieve and why it can't be done in a single (generic?) class.Derived.