- #1
JonnyG
- 234
- 45
I have an abstract class template, BinNode<E> and another class template, BSTNode<Key, E>, which is derived from BinNode<E>. Here is the relevant pieces of code from each template:
And
I figured that the compiler will implicitly convert a BSTNode pointer to a BinNode pointer, allowing me to set the parameter type of BSTNode::setLeft to a BSTNode pointer, because that's what I really want. But if I do that then it won't compile. I guess the parameter type has to match exactly. So I am forced to make the parameter type of BSTNode::setLeft be a BinNode pointer then downcast it in the function body. Fair enough.
But now look at the function left in both classes. The return type of BinNode::left is a BinNode pointer, but the return type of BSTNode::left is a BSTNode pointer. So the compiler can do the implicit conversion if it's the return type but not if it's the parameter type?
Is there a reason for this besides "that's just the way the language was designed"?
BinNode:
template <typename E> class BinNode {
public:
virtual BinNode<E>* left() const = 0;
virtual void setLeft(BinNode<E>*) = 0;
};
And
BSTNode:
template <typename Key, typename E> class BSTNode : public BinNode<E> {
public:
BSTNode<Key, E>* left() const override { return lc; }
void setLeft(BinNode<E>* l) override { lc = static_cast<BSTNode*>(l); }
};
I figured that the compiler will implicitly convert a BSTNode pointer to a BinNode pointer, allowing me to set the parameter type of BSTNode::setLeft to a BSTNode pointer, because that's what I really want. But if I do that then it won't compile. I guess the parameter type has to match exactly. So I am forced to make the parameter type of BSTNode::setLeft be a BinNode pointer then downcast it in the function body. Fair enough.
But now look at the function left in both classes. The return type of BinNode::left is a BinNode pointer, but the return type of BSTNode::left is a BSTNode pointer. So the compiler can do the implicit conversion if it's the return type but not if it's the parameter type?
Is there a reason for this besides "that's just the way the language was designed"?