C++ for Embedded · Interview question

Why must template definitions go in header files?

A strong answer

Because a template isn't compilable code until it's instantiated with concrete types, and the compiler needs the full definition visible at each point of instantiation to generate that code. If you put a template's body in a .cpp, other translation units see only a declaration, the compiler has nothing to instantiate from when they use it, and you get "undefined reference" link errors for the specific instantiations. Putting the definition in a header makes it visible everywhere it's used, so each translation unit can instantiate what it needs. This is why the STL and most template libraries are header-only. (There are workarounds like explicit instantiation in a .cpp for a known, fixed set of types, but the default and idiomatic approach is header-only.)

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

Templates: The Basics

Write a function or class once and have the compiler stamp out a type-specific version for each use: generic code with zero runtime cost, plus the code-bloat tradeoff to watch.

More Templates: The Basics questions

Browse all 472 interview questions
Why must template definitions go in header files? | EmbeddedPrep.io