Sobes.tech
Junior — Middle

How is the mechanism of polymorphism implemented in the C++ language?

sobes.tech AI

Answer from AI

In C++, the mechanism of polymorphism is implemented through virtual functions and inheritance. Polymorphism allows objects of different classes related by inheritance to use the same interface but with different implementations.

For this, functions are declared as virtual in the base class, and overridden in derived classes. When called through a pointer or reference to the base class, the version of the function corresponding to the actual type of the object will be invoked.

Example:

class Base {
public:
    virtual void show() { std::cout << "Base" << std::endl; }
};

class Derived : public Base {
public:
    void show() override { std::cout << "Derived" << std::endl; }
};

Base* obj = new Derived();
obj->show(); // Will output "Derived"

This is dynamic (runtime) polymorphism in C++.