Home > Back-end >  Why does an overriden template class method still get compiled?
Why does an overriden template class method still get compiled?

Time:10-06

When I create a templated class with a virtual function, and override the function in a derived class, the base function still tries to get compiled. Here is the minimal reproducible example:

#include <iostream>

template<typename T>
class Base
{
public:
    virtual void Method()
    {
        static_assert(false);
    }
};

class Derived : public Base<int>
{
public:
    void Method() override
    {
        std::cout << "Hello, World!";
    }
};

int main()
{
    Derived d{};

    d.Method();

    return 0;
}

Why does the base method still try to compile when it is overriden?

CodePudding user response:

First, it needs to be compiled as user can instantiate Base<T> and directly call Method() on it. If you wanted to make it non-callable, use virtual void Method() = 0; for abstract functions.

Second, not only compiled, it's actually accessible from Derived: you can call it e.g. from Derived::Method(), as Base<int>::Method().

  •  Tags:  
  • c
  • Related