Overriding base template class method

How do you override a base templatized class method (that is, a template class with a non-template method) in a child?

#include <Windows.h>
#include <iostream>

struct S{};

template <typename T>
class Base
{
public:
    Base()
    {
        Init(); // Needs to call child
    }

    virtual void Init() = 0; // Does not work - tried everything
    // - Pure virtual
    // - Method/function template
    // - Base class '_Base' which Base extends that has
    //      pure virtual 'Init()'
    // - Empty method body
};

class Child : public virtual Base<S>
{
public:
    virtual void Init()
    {
        printf("test"); // Never gets called
    }
};

int main()
{
    Child foo; // Should print "test"

    system("pause");
    return 0;
}

I know the technique to pass the child class type as a template argument to the base class and then use a static_cast, but it's just so unclean to me for something that should be incredibly easy.

I'm sure there is some fundamental idea behind templates that I am just not grasping, because I've been searching for hours and can't find any code or solutions to this particular scenario.

Upvotes: 0

Views: 1167

Answers (1)

Luchian Grigore
Luchian Grigore

Reputation: 258548

Calling virtual methods from constructors is a bad idea, as it doesn't get the behavior you expect. When the constructor of Base executes, the object is not yet fully constructed and is not yet a Child.

Calling it outside the constructor would work.

Upvotes: 3

Related Questions