Skip to content

O) Polymorphism

kalinosia edited this page Mar 13, 2021 · 5 revisions

Base class + Inheritance + Pointers/References

  • The most important feature of OOP is polymorphism.​
  • It’s a technique that allows to have one interface with many implementations.​
  • User can rely on interface behaviour – no matter, which implementation is actually in use.​
  • Interface of a car is always the same, no matter which​car from which producer user chooses.
  • Because of that, once user learns to drive a car, user can​ drive any car there is. Despite the fact that the internal parts ​ of the car might be completely different. It’s all hidden behind​ convenient and simple interface. -[Implementation]

Polimorphism in C++ :

  • Applied during compilation
    • Static Polymorphism​ - Overloading methods, functions and operators.
    • Parametric Polymorphism​ - Achieved with templating.
  • Applied in runtime
    • Dynamic Polymorphism

In order to use polymorphism at least 2 classes are needed:​

  • a class which defines interface using virtual methods and a class which implements or overrides that interface.​
  • A class having virtual methods is called polymorphic class.​
struct Interface {
    virtual void say()=0;
}
class PolymorpicClass{
public:
    virtual void say(){
        std::cout<<"Hello"<<std::endl;
    }
}
  • Virtual methods are declared using keyword virtual. Once method is declared virtual, it remains virtual in all subclasses.
  • Special form of virtual method is so called pure virtual method. Classes with at least one pure virtual method defined cannot be instantiated – this is used to declare interfaces, or abstract base classes.
  • Non-pure virtual methods are basically normal methods, just declared with virtual keyword. Such methods can have a default implementation, that can be changed by sublclass if needed.
  • New class must be defined for each new implementation of virtual method. Class that provides implementation has to inherit from class which defines interface.
  • We don’t have to repeat virtual keyword.
  • It is quite common in polymorphic subclasses to mark virtual methods with override keyword. The compiler will complain if there is nothing virtual to override. void say() override { ....
int main(){
First first;
Second second; //Create instances of our derived classes

Interface* ptr = &firs; //Create pointer of base type and initialize it with address of first
ptr->say();

ptr = &second; //change the pointer and point it to second
ptr->say();

Interface& ref = first; //We can use references 
ref.say();

return 0;
}

The rule is simple: if class has at least one virtual method, destructor of that class must be virtual to ensure that all destructors will be called. !!!

Clone this wiki locally