Login to manage your account

Please enter a valid email address.
Forgot Password?
Please enter a valid password.
OR

Don't have an account yet? Sign up

What are templates in C++, and what is the difference between compile-time and runtime polymorphism?

A template is a blueprint the compiler uses to generate code for each type you instantiate it with. std::vector<int> and std::vector<string> are entirely separate generated classes.

template <typename T>
T max_of(const T& a, const T& b) {
    return a > b ? a : b;
}

Compile-time polymorphism (templates):

  • Type resolution happens during compilation, so calls can be inlined and there is no runtime overhead.
  • Costs: longer compile times, larger binaries from code generated per type, and historically dreadful error messages — which is what C++20 concepts were introduced to fix.

Runtime polymorphism (virtual functions):

  • The type is resolved through the vtable while the program runs.
  • Costs an indirection and prevents inlining, but lets you store heterogeneous types behind one base pointer and choose behaviour based on runtime data.

How to choose: if the set of types is known at compile time and performance matters, use templates. If you need a collection of different types handled uniformly, or the type depends on runtime input such as a configuration file, use virtual functions.

Note: Templates must generally be defined in headers, because the compiler needs the definition at each instantiation point. That is why STL headers are so large.

All C++ interview questions

Login to manage your account

Please enter a valid email address.
Forgot Password?
Please enter a valid password.
OR

Don't have an account yet? Sign up as