template
class Node
{...};
int main
{
Node* ptr;
ptr = new Node;
}
Will fail to compile I have to to declare the
The simple answer is because C++ uses (fairly) strict static type
checking. Node
is a completely unrelated type to Node
,
and when the compiler sees ptr->doSomething()
, it has to know whether
to call Node
or Node
.
If you do need some sort of dynamic generality, where the
actual type ptr
will point to will only be known at runtime, you need
to define a base class, and derive from that. (It's a fairly common
idiom for a class template to derive from a non-template base, precisely
so that the generality in the pointers can be resolved at runtime.)