Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This actually illustrates one of the coolest and most useful features of C++: Temporary variables. Since you specified that the string reference is <code>const</code>, the compiler allows you to pass a reference to a temporary value to that function. So, here's what's happening behind the scenes with <code>Dude d2 = Dude("bye");</code>:</p> <ul> <li>The compiler determines that the best constructor to use is <code>Dude::Dude(const string &amp;)</code>. How this choice is made is a whole different topic.</li> <li>However, in order to use that constructor you need a <code>string</code> value. Now, <code>"bye"</code> is a <code>const char[4]</code>, but the compiler can trivially convert that to a <code>const char *</code>, and <em>that</em> can be turned into a <code>string</code>. So, an anonymous temporary variable (call it <code>temp1</code>) is created.</li> <li><code>string::string(const char *)</code> is invoked with <code>"bye"</code>, and the result is stored in <code>temp1</code></li> <li><code>Dude::Dude(const string&amp;)</code> is invoked with a reference to <code>temp1</code>. The result is assigned to <code>d2</code> (actually, it is assigned to another temporary variable and the copy constructor for <code>Dude</code> is invoked with a const reference to it and <em>that</em> is assigned to d2. But in this case the result is the same.)</li> <li><code>temp1</code> is discarded. This is where the string destructor <code>string::~string()</code> is run on <code>temp1</code></li> <li>Control passes to the next statement</li> </ul>
    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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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