Note that there are some explanatory texts on larger screens.

plurals
  1. POReducing parent-child class code duplication
    primarykey
    data
    text
    <p>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().</p> <pre><code>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() {} } </code></pre> <p>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?</p> <p><strong>UPDATE:</strong> 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).</p> <pre><code>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 */ } </code></pre> <p><strong>UPDATE2</strong> 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.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload