Note that there are some explanatory texts on larger screens.

plurals
  1. POMultiple Inheritance with clashing methods
    text
    copied!<p>I am writing some templated pure virtual base classes that are multiply inherited and discovered a minor oddity in the process. The crux of it is, if you define the same method in two base classes, inheriting from both compiles and works fine and it appears that you only need a single definition in the derived class. I am curious as to what is going on behind the scenes here, is this correct and planned behaviour or a dangerous compiler oversight?</p> <p>See below for illustrative code sample:</p> <pre><code>namespace { template &lt;typename T_NumType&gt; class InheritFrom { public: virtual void doSomething(const T_NumType&amp; numType) = 0; virtual void sharedMethod() = 0; }; // class class MultipleInheritor : public InheritFrom&lt;int&gt;, public InheritFrom&lt;float&gt; { public: void doSomething(const int&amp; numType) {} void doSomething(const float&amp; numType) {} void sharedMethod() {} // one definition here }; // class } int main(int argc, char** argv) { MultipleInheritor mult; mult.doSomething(5); mult.sharedMethod(); } </code></pre> <p>EDIT:<br> The answers below and looking at the C++98 standard finally cleared this up for me.</p> <p>From 10.3: Virtual Functions:</p> <blockquote> <p>in any well-formed class, for each virtual function declared in that class or any of its direct or indirect base classes there is a unique final overrider that overrides that function and every other overrider of that function.</p> </blockquote> <p>So this means that for any virtual function a single <em>final overrider</em> will be found. This is done through the rules detailed in 10.2: Member Name Lookup. </p> <p>So in the case I have presented there are indeed two base class functions and due to member name lookup the single function in the derived class is determined as the <em>final overrider</em> for both. So what I have is perfectly well formed and a logical result of the workings of the C++ compiler.</p>
 

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