Consider the following code. Is it guaranteed that Derived<int>::foo()
will be instantiated? foo()
is virtual and is called by a non-virtual function of the base class.
#include <iostream>
class Base
{
public:
void bar() { foo(); }
private:
virtual void foo() = 0;
};
template <typename T> class Derived: public Base
{
public:
Derived(T t_) : t(t_) {}
private:
void foo() override { std::cout << t; }
T t;
};
Derived<int> make_obj()
{
return Derived<int>(7);
}
Base class having virtual function can be instantiated i.e. its object can be made. Base class having pure virtual function becomes abstract i.e. it cannot be instantiated. If derived class do not redefine virtual function of base class, then it does not affect compilation.
A class template can indeed contain virtual or pure virtual functions. This was employed by Andrei Alexandresu in "Modern C++ Design" to implement the visitor pattern using templates and type lists.
Implicit instantiation means that the compiler automatically generates the concrete function or class for the provided template arguments. In general, the compiler also deduces the template arguments from the function's arguments. In C++17, the compiler can also deduce the template arguments for class templates.
The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation.
Standard section 14.7.1/11 says
It is unspecified whether or not an implementation implicitly instantiates a virtual member function of a class template if the virtual member function would not otherwise be instantiated.
However, for a typical vtable implementation, instantiating any constructor of the class requires a vtable for the class to exist, which must contain a pointer to the specialization's virtual function definition. So in practice the virtual function will probably be instantiated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With