Search⌘ K
AI Features

CRTP (Static Polymorphism)

Explore how to convert dynamic polymorphism into static polymorphism using the Curiously Recurring Template Pattern (CRTP) in C++. Understand the template-based approach to efficient compile-time method resolution and how it improves runtime efficiency by eliminating virtual tables.

Dynamic polymorphism code

Let’s look at the same code that we used in the dynamic polymorphism section.

C++
#include <iostream>
using namespace std;
class Person{
public:
virtual void print(){
cout<<"The is Person base class"<<endl;
}
};
class Student: public Person{
public:
void print(){
cout<<"This is Student derived class"<<endl;
}
};
int main() {
Person *obj1= new Person();
obj1->print();
Person *obj2= new Student();
obj2->print();
}

In the code above, we have the base class Person inherited by the derived class Student. We can see that the type print() function is called depending on the object type. This call to the print() function will be resolved at the runtime (dynamic polymorphism). Our job is to change ...