The problem is,
List<int>
a different class than
List<double>
. So LinkedList<int> and LinkedList<double> won't share a common base class, and polymorphic use is inapplicable.
Templates were "hacked" into Java because they couldn't change the JVM to copy the C++ implementation at the time. That's why that inheritance relationship exists between two different things. Plus, in C++, not everything is an object, some things are abstract data types.
In Java, you don't create objects on the stack, they're created on the heap. Object declarations really declare pointers to objects. That's why you need to use new or a creator on them before you use them.
So the equivalent of Java:
In C++, you'd be more explicit that you've created a pointer:
Back in the old days, Rogue Wave Tools.h++ provided RWPtr... and RWVal... variants for its containers.
http://docs.roguewave.com/legacy-hpp/tlsref/index.html#Class%20Hierarchy
It's possible to implement a polymorphic linked list, but we tend not to do that kind of thing in that way. You'd simply declare a linked list of objects, and stick whatever you like in it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
class Object;
class LinkedList
{
struct Node {
Object* data;
Node* prev, next;
Node(Object* obj) : data(obj), prev(nullptr), next(nullptr) {}
};
Node *m_head, *m_tail;
public:
void append(Object* obj);
void prepend(Object* obj);
//...
};
|