Note that there are some explanatory texts on larger screens.

plurals
  1. POC++: Is it possible to inherit the assignment operator?
    primarykey
    data
    text
    <p>The following C++ code doesn't compile:</p> <pre><code>class BaseA { protected: BaseA &amp;operator = (const BaseA &amp;rhs); }; template&lt;typename T&gt; class BaseB { public: T &amp;operator = (const T &amp;rhs) { return *static_cast&lt;T *&gt;(this); }; }; class Derived : public BaseA, public BaseB&lt;Derived&gt; { }; int main() { Derived foo; Derived bar; foo = bar; return 0; }; </code></pre> <p>When I try to compile this I get a complaint that <code>BaseA &amp;BaseA::operator = (const BaseA &amp;)</code> is undefined. There are several other questions like this on stackoverflow however they all seem to concern the compiler auto-generating a <code>Derived &amp;Derived::operator = (const Derived &amp;)</code> function which calls <code>BaseA::operator = (const BaseA&amp;)</code>. In this case though <code>Derived</code> should already be inheriting a function with that exact signature from <code>BaseB&lt;Derived&gt;</code>. If I follow the advice on another question and add <code>using BaseB&lt;Derived&gt;::operator =;</code> to <code>Derived</code> the compiler complains that <code>Derived &amp;operator = (const Derived &amp;)</code> cannot be overloaded.</p> <p>Is it simply not possible for a class to inherit this operator?</p> <p><strong>Edit:</strong> To be clear, I'm confused why the compiler is giving <code>Derived</code> a default <code>Derived &amp;operator = (const Derived &amp;)</code> when it already inherits <code>T &amp;operator (const T &amp;) where [T = Derived]</code> from <code>Base&lt;Derived&gt;</code>. I can understand why the default copy assignment operator would normally be created and override any inherited assignment operators but in this case <code>Derived</code> is inheriting an operator with <em>the exact same</em> signature as its copy assignment operator. Is there a way to write <code>BaseB</code> so that its subclasses use this operator?</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