Hi, I have a question about cloning objects in polymorphic classes:
In a lab we are doing in school we are going to create an expression tree, looking for example like this when it's printed:
which represents the expression 5*7+6 in tree form. Each node in the tree is of a class called node, then there's a subclass called node_operator. Each class under node is supposed to have a clone function, so that it is possible to clone a whole tree by just cloning the node at the lowest level.Code:5 / * \ 7 / + \ 6
node_operator in turn, is an abstract class which have subclasses called node_plus, node_minus, node_times etc. Each object which is of a derived class from node_operator will have two and only two data members, left_node and right_node. To clone a object from any subclass of node_operator, it will be the exact same code:
Where x is the name operator. Since x is different for every subclass, the same function can't be used, hence we need a virtual clone function. What I would like to do is something like this (only having to write the function once instead of having to write almost the same code in every subclass):Code:node_x* node_x::clone() { return new node_x(left_child->clone(), right_child->clone()); }
If only typeof would have existed in C++ (as it does in C) the code would have worked, and the function I mentioned above (that one with node_x) would have successfully been copied to every subclass node_x. But now typeof doesn't exist in C++. Can I use something else instead of typeof, or do I have to write the clone function in every subclass? Having to write the same code in every subclass feels bad. Besides, the risk of creating a bug will increase. Why did they remove typeof from the beginning, when they created C++ from C?Code:virtual node_operator* clone(); ... virtual node_operator* node_operator::clone(){ return new typeof(this*) (left_child->clone(), right_child->clone()); }