Sobes.tech
Junior — Middle

How to distinguish static polymorphism from dynamic polymorphism in object-oriented programming?

sobes.tech AI

Answer from AI

Static and dynamic polymorphism differ in the time of method call resolution:

  • Static polymorphism (compile-time polymorphism) is implemented through templates and function/operator overloading. The decision on which function to call is made at compile time.

  • Dynamic polymorphism (runtime polymorphism) is achieved using virtual functions and inheritance. The method call is determined during program execution via the virtual table (vtable) mechanism.

Example of dynamic polymorphism:

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"

Example of static polymorphism with templates:

template<typename T>
void print(const T& value) {
    std::cout << value << std::endl;
}

print(5);       // Call for int
print("text"); // Call for const char*

Thus, the key difference is the time of selecting the specific implementation: compilation for static and execution for dynamic.