Important: Please read the Qt Code of Conduct -

Advice: pure virtual method in base class implemented in subclass

  • Hi all,
    what I'd like to achieve is something like this:

    @class A{
    virtual myType* createMyType() = 0;
    void doSomeWork(){ createMyType(); }

    class B : public A {
    myType* createMyType() { ... }


    (I mixed the declaration and the definition for brevity).
    So in the base class I'd like to have a pure virtual method that is used by another (not virtual) method in the base class itself. In the subclass I'd like to implement the virtual method so to change the behavior, but this is not working since the base class gives me a "pure virtual method call" in the doSomeWork method. Is there a way to achieve this (or a better pattern to do this)?

  • AFAIK, this is possible, as long as the call is not made from the constructor. During construction, the type is not yet complete, and virtual function calls fail miserably. However, after construction, it should work just fine.

  • Ah I see... in fact the call is in my constructor path. I think I have to refactor the code, since having a polymorphic method within the constructor is quite dangerous.

  • Calling virtuals in constructors: Not only it's dangerous, it plain doesn't work.

    This "C++ FAQ": shows some recipes how to circumvent that problem.

  • [quote author="Volker" date="1324298291"]Calling virtuals in constructors: Not only it's dangerous, it plain doesn't work.


    Thanks, I know it is bad. In fact I'm going to change it. I simply did not realize from the compiling error that it was in my constructor path.

Log in to reply