0

As you can see from here not all template functions are being compiled in a template class. Standard says, that if the method or a member is not being used, it is not being compiled. Cool feature, indeed! Now, lets discuss the following hierarchy:

class A
{
  virtual void f() {};
};

template <typename T>
class B : public A
{
  virtual void f () override
  {
       // do something dangerous
  }
}

You will never know if B<int>::f is being called, right? The reason is that you can call a function B::f with dynamic binding and you never know if A* points onto B type object or other typed object that is derived from A. So how the compiler should handle this case?

A* ptr = nullptr;
if (i > 0)
{
    ptr = new B<int>();
}
ptr->f();

How does compiler guess/spot this case to generate B<int>::f

IMPORTANT RELATED QUESTION: Can a C++ class member function template be virtual?

Community
  • 1
  • 1
Narek
  • 38,779
  • 79
  • 233
  • 389

1 Answers1

1

Somewhere in your program you have to use B<int> or a type derived there of to create an instance. At that point the template is instantiated and the code for it is generated. There is also explicit instantiation. Check out cppreference.com for details.

Kurt Stutsman
  • 3,994
  • 17
  • 23
  • Kurt, I have wrote `new B()`, hence it know that for `int` the code should be generated, but the question is how does it know that I am going to use `B::f`? – Narek Mar 10 '16 at 05:19
  • 1
    Because it's a virtual function. The compiler has to generate the virtual functions for an instantiated type because it cannot know if it is called or not in general. – Kurt Stutsman Mar 10 '16 at 05:23
  • Your comment is the answer. So for template class all virtual functions are generated. – Narek Mar 10 '16 at 06:10