Note that there are some explanatory texts on larger screens.

plurals
  1. POC++ copy constructor invocation
    primarykey
    data
    text
    <p>As far as i know, a copy constructor is invoked in the following scenarios :</p> <pre><code>1) Pass by value 2) Return by value 3) When you create and initialize a new object with an existing object </code></pre> <p>Here's the program :</p> <pre><code>#include &lt;iostream&gt; using namespace std; class Example { public: Example() { cout &lt;&lt; "Default constructor called.\n"; } Example(const Example &amp;ob1) { cout &lt;&lt; "Copy constructor called.\n"; } Example&amp; operator=(const Example &amp;ob1) { cout &lt;&lt; "Assignment operator called.\n"; return *this; } ~Example() { cout&lt;&lt;"\nDtor invoked"&lt;&lt;endl; } int aa; }; Example funct() { Example ob2; ob2.aa=100; return ob2; } int main() { Example x; cout &lt;&lt; "Calling funct..\n"; x = funct(); return 0; } </code></pre> <p>The output is:</p> <blockquote> <p>Default constructor called.</p> <p>Calling funct..</p> <p>Default constructor called.</p> <p>Assignment operator called.</p> <p>Dtor invoked</p> <p>Dtor invoked</p> </blockquote> <p>Please correct me, IIRC the following sequence of calls should occur :</p> <p>1) Constructor of x is called</p> <p>2) Constructor of ob2 is called</p> <p>3) The function returns and so copy constructor is invoked (to copy ob2 to unnamed temporary variable i.e funct() )</p> <p>4) Destructor of ob2 called </p> <p>5) Assign the unnamed temporary variable to x</p> <p>6) Destroy temporary variable i.e invoke its destructor</p> <p>7) Destroy x i.e invoke x's destructor</p> <p>But then why copy constructor is not invoked and also only 2 calls to dtors are there whereas i expect 3.</p> <p>I know compiler can do optimizations, however, is my understanding correct ?</p> <p>Thanks a lot :)</p> <p>Regards</p> <p>lali</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.
 

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