C++ – Call pure virtual function from parent class

cclass

I'm very new to c++, but I think I understand what is going on. The parent class is trying to call the pure virtual member function in the parent class. I thought that by overriding the virtual function in the child class, it would be called instead.

What am I doing wrong?

Provided for me in parent.h

class Parent
{
public:
virtual void run() = 0;
protected:
/** The function to starter routine and it will call run() defined by the
 * appropriate child class.
 * @param arg Arguments for the starter function
 */
static void * init (void * arg);
};

I'm trying to do this in parent.cpp

void * Parent::init(void * arg)
{
  run();
}

In my child.h I have this:

class Child : public Parent
{public:
//...
virtual void run();
//...
};

And in child.cpp I have:

void Child::run()
{
   sleep(10);
}

The function init in parent.cpp is where this fails to compile. How do I call a derived function from the parent class? All my googleing has only turned up notes about not calling virtual functions in the child's constructor.

Any help at all would be appreciated.

Best Answer

run() is an instance member. Parent::init is a static (class-level) member. So in your init() implementation, there is no instance (of Parent or Child) available on which to call run().