For a project to score high my program need to support polymorphism. But it's confusing for me. This project is about trains.
I have made few classes. Among them two them are driver class and train class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
class train{
void moveTrain();//this method will make the train move from one
//location to another
};
class driver{
void moveTrain(); //driver will move the train
};
so by using the moveTrain method both train and driver object will move train from location to another. But I am not sure if it's polymorphism. If not what is polymorphism actually?
thx in advance
Polymorphism is connected to inheritance, and is basically about making one object behave like another. It is achieved through dynamic memory allocation.
#include <iostream>
class MilitaryUnit {
public:
// virtual, because it will be overridden
virtualvoid id() {
std::cout << "I'm just a MilitaryUnit!" << std::endl;
}
// destructor for a base class must be virtual
virtual ~MilitaryUnit() {
}
};
// inheritance from MilitaryUnit
class Airplane: public MilitaryUnit {
public:
void id() {
std::cout << "I'm an Airplane!" << std::endl;
}
};
class Tank: public MilitaryUnit {
public:
void id() {
std::cout << "I'm a Tank!" << std::endl;
}
};
class Marksman: public MilitaryUnit {
public:
void id() {
std::cout << "I'm a Marksman!" << std::endl;
}
};
int main() {
// array of five pointers
MilitaryUnit *team_members[5];
team_members[0] = new Airplane;
team_members[1] = new Marksman;
team_members[2] = new Tank;
team_members[3] = new Airplane;
team_members[4] = new Marksman;
// will not say "I'm just a MilitaryUnit!"
for (int i=0; i < 5; ++i)
team_members[i]->id();
// for every new, there must be a delete
delete team_members[0];
delete team_members[1];
delete team_members[2];
delete team_members[3];
delete team_members[4];
}
I'm an Airplane!
I'm a Marksman!
I'm a Tank!
I'm an Airplane!
I'm a Marksman!