Note that there are some explanatory texts on larger screens.

plurals
  1. POvirtual function question
    primarykey
    data
    text
    <pre><code>#include "stdafx.h" #include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; class Helper { public: Helper() { init(); } virtual void print() { int nSize = m_vItems.size(); std::cout &lt;&lt; "Size : " &lt;&lt; nSize &lt;&lt; std::endl; std::cout &lt;&lt; "Items: " &lt;&lt; std::endl; for(int i=0; i&lt;nSize; i++) { std::cout &lt;&lt; m_vItems[i] &lt;&lt; std::endl; } } protected: virtual void init() { m_vItems.push_back("A"); } std::vector&lt;std::string&gt; m_vItems; }; class ItemsHelper : public Helper { public: ItemsHelper() { } protected: virtual void init() { Helper::init(); m_vItems.push_back("B"); } }; int _tmain(int argc, _TCHAR* argv[]) { ItemsHelper h; h.print(); } </code></pre> <p>This output's that the size of the vector is 1. I expected the size to be 2 because in the ItemsHelper::init function I called the base class <code>Helper::init()</code> function, then I add a second item to the vector. The problem is, the ItemsHelper::init doesn't get called, the base class init function gets called instead.</p> <p>I want the ItemsHelper::init function to get called, and I can do that by calling the init function in the ItemsHelper ctor rather than in the base class. <strong>BUT, the question is</strong>, is there a better way to achieve that and still keep the call to the init() in the base class? Because what if I want to create a Helper object instead of a ItemsHelper, then the init function would never get called.</p> <p>btw, this is a simplified version of a issue I'm seeing in a much larger object, I just made these objects up for example.</p>
    singulars
    1. This table or related slice is empty.
    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.
 

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