polymorphism

Hi guys

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.

Read here: http://www.cplusplus.com/doc/tutorial/polymorphism/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <iostream>

class MilitaryUnit {
public:
    // virtual, because it will be overridden
    virtual void 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!
polymorphism is the ability to use the same expression to denote different operations

a simple google search will solve your problems
http://www.cplusplus.com/forum/beginner/2530/

reply if you have any other questions
thanks for reply guys.
does that mean that it's not possible to use polymorphism without inheritance?
Without inheritance, the compiler would complain that the types are incompatible and it wouldn't work. Try it yourself.

thanks for reply guys.
does that mean that it's not possible to use polymorphism without inheritance?

yes
Topic archived. No new replies allowed.