Polymorphism

Polymorphism

Polymorphism is the occurrence of the object in multiple forms. Polymorphism in C++ is tied to inheritance and pointers. Pointer to a base class is compatible with a pointer to a derived class. Base class has virtual member functions which we override in a derived class. Example:

#include <iostream>
class BaseClass{
public:
	virtual void doSomething(){
		std::cout << "Base class." << std::endl;
	}
	virtual ~BaseClass(){} // Base class should also have a virtual destructor
};

class DerivedClass : public BaseClass{
public:
	void doSomething() override {
		std::cout << "Derived class." << std::endl;
	}
};

int main(){
	BaseClass* p = new DerivedClass;
	p->doSomething(); // calls DerivedClass' doSomething() function
	delete p;
}

Explanation

Here we are accessing a derived class method through a base class pointer. We mark a base class function as virtual and override its behavior in subsequent derived classes. If we omitted the derived class member function definition then the base class function would be invoked.

We can have multiple derived classes and decide which one we want to instantiate:

#include <iostream>
class BaseClass{
public:
	virtual void doSomething(){
		std::cout << "Base class." << std::endl;
	}
    virtual ~BaseClass(){}
};

class DerivedClass : public BaseClass{
public:
	void doSomething() override {
		std::cout << "Derived class." << std::endl;
	}
};
class SecondDerivedClass : public BaseClass{
public:
	void doSomething() override {
		std::cout << "Second Derived class." << std::endl;
	}
};

int main(){
	BaseClass* p = nullptr;
	if (1){ // some condition
		p = new SecondDerivedClass;
	}
	else{
		p = new DerivedClass;
	}
	p->doSomething(); // access Member function of the chosen instantiated class
	delete p;
}

As you can see we are using one pointer to access different classes member functions. Instead of raw pointers it is better to use the smart pointers:

#include <iostream>
#include <memory>
class BaseClass{
public:
	virtual void doSomething(){
		std::cout << "Base class." << std::endl;
	}
	virtual ~BaseClass(){}
};

class DerivedClass : public BaseClass{
public:
	void doSomething() override {
		std::cout << "Derived class." << std::endl;
	}
};

int main(){
	std::shared_ptr<BaseClass> p = std::make_shared<DerivedClass>();
	p->doSomething();
}