I have created a templated BinaryTree class to use it for cases where I need binary trees (ASTs, decision, etc.). The idea was to put most of the tree behavior in the base class and have very slim (for basic tree behavior) derived classes that can focus on implementing other needed specialized behavior (AST, decision, etc.). This is the attempted code:
template< class T > class Base
{
private:
T value{};
Base* left, * right;
public:
Base() : left{ nullptr }, right{ nullptr } {};
Base(T val) : value{ val }, left{ nullptr }, right{ nullptr } {};
Base* GetRightLeaf() const{ return right; }
void SetRightLeaf(Base* node) { right = node; }
};
class DeriveBase :public Base<int>
{
public:
DeriveBase():Base(){}
DeriveBase(int val):Base(val){}
};
int main()
{
DeriveBase b1(1), b2(2), b3(3);
b2.SetRightLeaf(&b1);
DeriveBase* c = b2.GetRightLeaf(); //right here we get compiler error
}
The error is: a value of type “Base<int>“ cannot be used to initialize an entity of type “DeriveBase”. Now, I get it, these are two different types and that’s why I get the error. My question is, how can I make this work? Sure, you can say take the setter and getter out of the base class and implement them in the derived class. However, as I have mentioned above, I want as much of the specific “general” tree behavior as possible to be in the base class so that I can have “skinny” derived classes that can use as much functionality as possible from the base class.
Is this even possible?
ConfusedCpp is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.