1

I have several child classes that I would like to not have to rewrite certain initialized code for.. I've tried something like..

#include <iostream>

struct A {
   A() { init(); }
   virtual ~A() {}
   void init() { load(); }

   virtual void load() = 0;
};

struct B : public A {
    void load() { std::cout << "loading.." << std::endl; }
};

int  main(int argc, char* argv[])
{
    A* a = new B; delete a;
    return 0;
}

Which gives the runtime error/exception - "pure virtual method called".. I've read through other threads that explain that this is not possible; but I don't see any solution besides being forced to re-write the same code over and over in the child class. Is there a better way to encapsulate this? (Other than doing this in the child constructor..)

  • 5
    Remember that when constructing objects in an inheritance hierarchy, that the base classes are constructed (fully) prior to the derived class being constructed. In your code, the constructor of `A` is executing on an object that is _not_ a `B`. Long story short, don't call virtual methods from constructors. – Chad Jan 14 '14 at 06:05

0 Answers0