template
class Node
{...};
int main
{
Node* ptr;
ptr = new Node;
}
Will fail to compile I have to to declare the
Why do I have to specify the type when declaring a pointer I haven't created the class yet, why does the compiler have to know what type it will be pointing to.
There are lots of things you're allowed to do with a pointer, just to list a very few:
For the compiler to generate code to do these efficiently, it needs to know the type of the pointer. If it defered the decisions until it saw the type of the pointer, then it would need to either:
And is it not possible to create a generic pointer and decide afterwards what type I want to assign it.
Kind of... you have many options:
void*
, but before it can meaningfully operate on the pointed-to-type again you'll need to manually cast it back to that type: in your case that means recording somewhere what it was then having separate code for every possibilityboost::any<>
- pretty much like a void*
, but with safety built inboost::variant<>
- much safer and more convenient, but you have to list the possible pointed-to types when you create the pointerNode
that declares the shared functions and member data you'd use to operate on any particular type of node, then the templated Node
class derives from that abstract Node
and implements type-specific versions of the functions. These are then called via a pointer to the base class using virtual
functions.