Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a virtual function of a template class implicitly instantiated?

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);
}
like image 717
BlindDriver Avatar asked Dec 15 '16 22:12

BlindDriver


People also ask

Can virtual function class be instantiated?

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.

Can a template class have virtual functions?

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.

What is implicit instantiation?

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.

What is the instantiation of the class template?

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.


1 Answers

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.

like image 124
aschepler Avatar answered Nov 15 '22 08:11

aschepler