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.
You're trying to call an instance method from a static method. You'll need to change
init()
to be an instance method (by removing thestatic
keyword) or else you'll need to call therun()
method using an object, e.g.obj->run()
orobj.run()
.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().
Look at this example that I recently provided here:
Do you know the actual type of
arg
: is it in fact aParent
instance? If so, then ...