I feel like this should be something simple but I have spent tons of time trying to figure out why I cannot make a linked list of different classes that inherit from the same abstract class
each of the classes (i.e. BadCruisingShootingAgent) I am pushing to the front of the linked list are inheriting from the abstract class Agent.
I am getting….
error: cannot declare field ‘Node::data’ to be of abstract type ‘Agent’
my main.cpp file reads:
int main()
{
LinkedList<Agent> *agentList= new LinkedList<Agent>();
agentList->push_front(*(new BadCruisingShootingAgent));
agentList->push_front(*(new BadFollowingDisarmedAgent));
agentList->push_front(*(new BadFollowingShootingAgent));
agentList->push_front(*(new BadStationaryDisarmedAgent));
agentList->push_front(*(new BadStationaryShootingAgent));
agentList->push_front(*(new GoodCruisingDisarmedAgent));
agentList->push_front(*(new GoodCruisingShootingAgent));
agentList->push_front(*(new GoodFollowingDisarmedAgent));
agentList->push_front(*(new GoodFollowingShootingAgent));
agentList->push_front(*(new GoodStationaryDisarmedAgent));
agentList->push_front(*(new GoodStationaryShootingAgent));
for(int i=0; i<agentList->size(); i++)
{
cout << agentList->at(i).getType()<<" "<<agentList->at(i).nextMovingDirection(10,10)<<" "<<agentList->at(i).shootingDirection(10,10)<<endl;
}
return(0);
}
I don’t understand why this does not work while if I just manually write there are no problems.
Agent *a= new BadCruisingShootingAgent;
cout << a->getType()<<" "<<a->extMovingDirection(10,10)<<" "<<a->shootingDirection(10,10)<<endl;
Then my linked list’s class function push_front is defined as:
template <typename T>
void LinkedList<T>::push_front(const T& val)
{
//make a new node
Node<T>* newOne = new Node<T>(val);
//push it onto the front of the list
newOne->next = this->head;
this->head = newOne;
//increase the length of the list by one
this->length++;
}
my node class is defined as:
template <typename T>
class Node
{
public:
Node(const T& d);
T data;
Node<T>* next;
};
template <typename T>
Node<T>::Node(const T& d)
: data(d)
{
this->next = NULL;
}
You can’t perform polymorphism on types that aren’t references or pointers. Thus, when you create a
LinkedList<Agent>, the underlying nodes are allocating anAgent, which can’t be created because it is an abstract type.Thus, using
LinkedList<Agent*>lets you polymorphically store different derived types in your linked list.