Interchangeable objects with polymorphism
•When you inherit a class from an existing one, you can threat objects of the derived class like objects of the base class: this means that an object of the base data type (or a pointer to it, or a reference to it) can store also an object of the derived data type:
•
http://www.alessandroogheri.com
•//we assume here that the class Derived is derived from the class Base
•Base B;
•Derived D;
•B = D; //legal
•D = B; //not legal
•Base *Bp; Derived *Dp;
•Bp = Dp; Bp = &B; Bp = &D; //all legal
•Dp = Bp; Dp = &B; //all not legal
•Base &Br = B; Derived &Dr = D;
•Br = Dr; Br = D; //all legal
•Dr = Br; Dr = B; //all not legal
•
•
Polymorphism is a concept peculiar to object oriented programming, and represents the capability of using an object of a derived class where one object of its base class is syntactically required.
This enforces again the is a relationship that we mentioned before: if an opel astra is a car, in C++ you can pass an opel astra object to every function which expects a car (it sound logical, hopefully!):
void start(car& c); // turns on a car...
opel_astra my_opel_astra;
start(my_opel_astra);
Please note that the other assignment directions are not legal, though: if you have a function that expects an opel you can not pass to it a generic car, since not every car must necessarily be an opel! (You could pass to the function an opel astra turbodiesel, though, as this is a more specialized class)
The advantages of polymorphism are that you can refactor code which must act on related- data types in a single function, which makes the design more concise and less error prone.