Skip to content

C++ Polymorphism 👷🏼‍♂️👷🏼‍♀️

(from ⇛ Javidx9's youtube video)

class diagram

Assuming that class A has a DoStuff() method and classes B and C override this method.

vector<A> vec;
...
vec[3].DoStuff();

Regardless of the derived class held in the vector at 3, A's DoStuff() method will always be called.

Pointers to the rescue

A* ob1 = new B();
A* ob2 = new C();

Now ob1 and ob2 will use the derived classes DoStuff() method.

This becomes more useful with the use of collections of pointers... for example...

vector<A *> vecs;

vecs.push_back(new B());
vecs.push_back(new C());

for(auto derived : vecs) derived->DoStuff();

Now any instance in the vector will use their own class's DoStuff() method.

Declaring a Base Class

Not Abstract

class A {
public:
    virtual DoStuff() {
        ...
    }
}

Abstract

Abstract classes cannot be instantiated. By declaring any method within the class as a pure function, the class cannot then be instantiated.

class A {
public:
    virtual DoStuff() = 0;
}

In this case DoStuff() is declared as pure by replacing it's body with =0;. Pure functions like this MUST be overriden.

Declaring a Derived Class

class B : public A {
public:
    void DoStuff() override
    {
        ...
    }
}

Declaring DoStuff() as an override with the override flag this signifies that this method is overriding the same one from the base class. override is optional, but it's very useful to include it.