Polymorphism
Polymorphism
Polymorphism
C++ Polymorphism
Major abstractions of C++
Data abstraction (using classes) Class relationships (using inheritance)
However, often upcasting does not offer the desired behavior Example
class Car { public: void start() { cout << "Car::start()" << endl; } }; class BMW : public Car { public: void start() { cout << "BMW::start()" << endl; } }; int main(int argc, char** argv) { Car *car = new BMW; car->start(); //Calls Car::start(), not BMW::start() delete car; }
Example: intro.cpp
Desired behavior
The type of the object, not the type of the pointer should determine the method to invoke
Example
class Car { virtual void start () { ... } // Car::start }; class BMW : public Car { virtual void start () { ... } //Redefinition: BMW::start redefines Car::start }; Car *car; BMW *bmw; car = new Car; car->f(x); //Invokes Car::f bmw = new BMW; b->f(x); //Invokes BMW::f car = new BMW; //UPCAST !!! car->f(x); //Invokes BMW::f since the objects type is BMW
Example: introvirtual.cpp
Base
Base
TypeInfo
Base*
TypeInfo
Derived*
Base*
Exception
Derived class may return Derived* instead of Base*
Behavior
In constructors, virtual methods of the current class are invoked Same applies to destructors
Example: exhaustiveexample.cpp
10
Car BMW VW
Lorry
Bike
11
Syntax
virtual method-signature = 0;
Examples
class A { virtual void f() = 0; }; class B { virtual void f(const int x&) const = 0; };
12
Usage
void switch_on(Lamp& l) { l.on(); } LightBulb lb; switch_on(nl); //Polymorphism LightBulb::on()
Example: purevirtual.cpp
13
Advantages
Code (new behaviors) can be added without requiring changes to other classes Easy implementation of interfaces
Disadvantages
Dynamic binding introduces run-time overhead
14
15
Example
Vehicle *v = new BMW BMW* bmw = dynamic_cast<BMW*> v; VW* vw = dynamic_cast<VW*> v; if( bmw != NULL ) { } else if( vw != NULL ) { }