Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><a href="https://stackoverflow.com/questions/3215756/operator-in-subclass/3215856#3215856">Martin told you what went wrong</a>, here's what you should do instead: </p> <pre><code>Bar bar; Foo&amp; foo = bar; // this works now </code></pre> <p>Now <code>foo</code> is a <strong><em>reference</em></strong> to a an object, and you can have base class references (and pointers, BTW) refer to objects of derived classes. </p> <p>However, this</p> <pre><code>bar = foo; </code></pre> <p>will never work (at least not implicitly) and it shouldn't. What you're trying to do here is to assign a base class object (or reference) to a derived class.<br> However, while a derived class can always stand in for a base class object, the opposite is not true. (You can't just mindlessly use any <strong><em>vehicle</em></strong> when what you need is a <strong><em>boat</em></strong>, because not all vehicles are boats, the vehicle you're using might be a <strong><em>car</em></strong> and you'd drown.) </p> <p>This is not to say that you cannot make it work. if you know how to create a derived class object from a base class object, you can write a function to do so. It's just that the compiler doesn't know how to make a <em>car</em> from a <em>vehicle</em>. </p> <p>As <a href="https://stackoverflow.com/questions/3215756/operator-in-subclass/3216152#3216152">solipist has shown</a>, such a conversion function can be a constructor. However, I would make conversion constructors explicit: </p> <pre><code>class Bar: public Foo { public: explicit Bar(const Foo&amp;); // } </code></pre> <p>The <code>explicit</code> keyword makes sure that the compiler will never attempt to call this constructor unless you say so. If you remove it, then this code would compile: </p> <pre><code>//void f(Foo); // you meant to call this, but forgot to include its header void f(Bar); // you didn't even know this was included Foo foo; f(foo); // won't compile with the above Bar class </code></pre> <p>and the compiler would silently generate this code: <code>f(Bar(foo));</code><br> While this seems handy at first, I think I have sooner or later been bitten by every single implicit conversions I allowed to creep into my code and had to remove them later. So many years ago I swore to never allow them anymore.<br> Note that even with the <code>explicit</code> conversion constructor you can still call <code>f(Bar)</code> with a <code>Foo</code> object - you just have to say so explicitly: </p> <pre><code>f(Bar(foo)); // compiles fine even with the explicit conversion constructor </code></pre>
 

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