I’m having a problem with polymorphism and parent-child relationships. Take the following two classes, and imagine in my application I create an object of ‘child’. Outside of the objects, the only function I call is update(), which in turn invokes everything else I need within the object. The only function in this sequence of calls that differs in ‘parent’ and ‘child’ is dosomething2().
class parent
{
public:
void dosomething1() {}; //amongst other things, calls dosomething2
void dosomething2() {};
void update() {}; //amongst other things, calls dosomething1
}
class child : public parent
{
void dosomething2() {}
}
I realized that if I create an object of ‘child’ and call update(), only the parent class functions will be called. I had to copy update() and dosomething1() to the child class, and then everything worked as expected. That’s not a very nice solution though because there is a lot of duplicate code – is there a way to improve this?
UPDATE:
Thanks to the answers provided, I updated the parent class with a virtual dosomething2() function. Now the correct function is invoked, and I don’t have to copy dosomething1() to the child class. Unfortunately, if I do not copy update() to the child class, I get a symbol lookup error (both parent and child are in a library together).
class parent
{
public:
void dosomething1() {}; //amongst other things, calls dosomething2
virtual void dosomething2() {};
void update() {}; //amongst other things, calls dosomething1
}
class child : public parent
{
void dosomething2() {}
/*void update() {}; //symbol lookup error if this is left uncommented */
}
UPDATE2
The symbol lookup error was not related to the code. I did a make clean, and then make (which builds a .so library and the executable) and now things work as expected.
You should use keyword
virtualin parent-class if you wantdynamic-polymorphism. And then reimplement or no reimplement virtual functions in child class.