Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat's the simplest way to satisfy a pure abstract method with methods from other base classes
    primarykey
    data
    text
    <p><strong>Edit:</strong> Per some comments, by simple I mean a) less code, b) easy to maintain, and c) hard to get wrong.</p> <p><strong>Edit #2:</strong> Also, using containment instead of private inheritance is not objectionable if it does indeed simplify the implementation of <code>InterfaceImpl</code>.</p> <p>Currently, the only way I know to do this is to have the implementer define the abstract method and delegate the call to the target base type's method. Example:</p> <pre><code>#include &lt;iostream&gt; #include &lt;memory&gt; class Interface { public: virtual void method1() = 0; virtual void method2(int x) = 0; }; class MethodOneImpl { private: void method1(int x) { std::cout &lt;&lt; "MethodOneImpl::method1() " &lt;&lt; x &lt;&lt; std::endl; } public: void method1() { method1(0); } }; class MethodTwoImpl { public: void myFunc(int x) { std::cout &lt;&lt; "MethodTwoImpl::myFunc(x)" &lt;&lt; x &lt;&lt; std::endl; } }; class InterfaceImpl : public Interface , private MethodOneImpl , private MethodTwoImpl { public: virtual void method1() { MethodOneImpl::method1(); } virtual void method2(int x) { MethodTwoImpl::myFunc(x); } }; int main() { std::unique_ptr&lt;Interface&gt; inf; inf.reset(new InterfaceImpl); inf-&gt;method1(); inf-&gt;method2(0); // This should be disallowed! // std::unique_ptr&lt;MethodOneImpl&gt; moi; // moi.reset(new InterfaceImpl); } </code></pre> <p>At first, I thought that perhaps this might solve the problem:</p> <pre><code>class InterfaceImpl : public Interface , private MethodOneImpl , private MethodTwoImpl { public: using MethodOneImpl::method1; // Obviously this wouldn't work as the method names don't match. //using MethodTwoImpl::??? }; </code></pre> <p>The first using statement will make both <code>MethodOneImpl::method1</code> methods be public, but it actually doesn't fulfill the contract with <code>Interface</code>, and it modifies the accessibility of <code>MethodOneImpl::method1(int)</code>. And obviously we couldn't use this solution with <code>method2</code> as the names don't match up.</p> <p>FWIW, I have what I think is a solution, but it is not part of the standard at all (in other words it won't compile). I was thinking of making a proposal to the C++ committee; if anyone has any advice, I'd appreciate any comments below (but please dont' submit the advice as an answer).</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.
 

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