POLYMORPHISM AND DATA ABSTRACTION
POLYMORPHISM
§ many
forms
§ Greek
o "poly" – many
o
"morph" form
§ the same
method can be called on different objects
§ they may
respond to it in different ways
§ all
Vehicles have a move method
§ Cars and
Truck drive
§ Airplanes
fly
#include
"Vehicle.h"
int
main(){
Vehicle v
("Transporter 54");
Airplane
a("Tornado 2431", 14);
LandVehicle
lv("My wheels");
Car
c("Ford Anglia 22");
Truck
t("Red pickup");
v.move();
a.move();
lv.move();
c.move();
t.move();
}
OUTPUT
Vehicle
constructor
Vehicle
constructor
Airplane
constructor
Vehicle
constructor
Land
vehicle constructor
Vechicle
constructor
Land
vehicle constructor
Car
constructor
Vechicle
constructor
Land
vehicle constructor
Truck
constructor
Vehicle
Transporter 54 moving
Airplane
Tornado 2431 flying
Land
Vehicle My wheels driving
Land
Vehicle Ford Anglia 22 driving
Land
Vehicle Red pickup driving
Polymorphic
behaviour
§ to get
polymorphic behaviour, we would like the version of move() to be determined at
run-time
§ if
moveVehicle is sent an Airplane object, it should get it to fly
§ do this by using the virtual keyword in the
first (base class) declaration of the polymorphic method
class
Vehicle { protected:
string
name;
public:
// other
members
virtual
void move() { cout << "Vehicle " << name << "
moving" << endl; } };
•
now it works
•
Vehicle Transporter 54 moving
•
Airplane Tornado 2431 flying
•
Land Vehicle My wheels driving
•
Land Vehicle Ford Anglia 22 driving
•
Land Vehicle Red pickup driving
•
polymorphism allows us to use a pointer to a
derived type object wherever a pointer to base type is expected
Car
c("Ford Anglia 22"); Vehicle * v2 = &c;
v2->move();
Vehicle & v3 = c; v3.move();
•
only works for pointer and reference types
•
they store an address – same size for all objects
Airplane a("Tornado 2431", 14);
Vehicle
v2 = a; v2.move();
•
trying to fit an airplane into a space meant for
any vehicle
•
can call the move() method, but we've lost the
wingspan member variable
•
Polymorphism:
•
Ability for objects of different classes to respond
differently to the same function call
•
Base-class pointer (or reference) calls a virtual
function
•
C++ chooses the correct overridden function in
object
•
Suppose print not a virtual function
Employee
e, *ePtr = &e;
HourlyWorker
h, *hPtr = &h;
ePtr->print(); //call base-class print function
hPtr->print(); //call derived-class print function
ePtr=&h; //allowable implicit conversion
ePtr->print(); // still calls base-class print
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.