Search⌘ K
AI Features

Comparison with Runtime Polymorphism

Explore the distinction between runtime polymorphism and compile-time programming in C++. Understand how inheritance and virtual functions impact performance compared to compile-time techniques. Learn to use if constexpr for creating efficient generic functions, such as a type-safe generic modulus, enhancing your code’s flexibility and performance.

Runtime polymorphism

As a side note, if we were to implement the with traditional runtime polymorphism, using inheritance and virtual functions to achieve the same functionality, the implementation would look as follows:

C++
struct AnimalBase {
virtual ~AnimalBase() {}
virtual auto speak() const -> void {}
};
struct Bear : public AnimalBase {
auto roar() const { std::cout << "roar\n"; }
auto speak() const -> void override { roar(); }
};
struct Duck : public AnimalBase {
auto quack() const { std::cout << "quack\n"; }
auto speak() const -> void override { quack(); }
};
auto speak(const AnimalBase& a) {
a.speak();
}

The objects have to be accessed using pointers or references, and the type is inferred at runtime, which results in a performance loss compared ...