Search code examples
c++virtual

Calling a virtual function before Implementation


So I have this kind of setup

class Base
{
public:
  Base();
  virtual void parse() = 0;
};

Base::Base()
{
  parse();
} 

class Sub : public Base
{
public:
  Sub();
  void parse();
};

Sub::Sub() : Base() {}

void Sub::parse()
{
  // DO stuff
}

I'm wondering if there's anway I can do something similar to this, right now I'm getting an error that says I can't call a pure virtual function which makes sense. Are there any keywords out there that I can use to make this work?

I think making parse() just virtual and not pure virtual would work, but I would like the user to have to overwrite it.


Solution

  • Invoking virtual member functions in a constructor (or destructor) will never make you end up in an overridden version of that function in a derived class.

    The reason is that base class constructors (destructors) are executed before (after) derived class' constructors (destructors). That means that the part of an object representing the derived class simply is not yet (not anymore) existing. And calling member functions on non-existing objects isn't possible.

    You will need to implement a form of two-phase construction (which isn't built into the language) in order to do what you want. Usually that's done by having a wrapping class first fully construct a Sub object and only then call parse() on it.