Note that there are some explanatory texts on larger screens.

plurals
  1. POtemporary and copy constructor
    primarykey
    data
    text
    <p>With the below program, I tried to experiment with the copy ctor, there is one point which is not clear, when function <code>f( )</code> returns it should use the copy-ctor to create a new object for <code>h2</code>, however I guess that is accomplished by the temporary object which uses the constructer of the object and then makes the copy however the destruction output shows that I am wrong on this reasoning... some clarification is appreciated on this problem ;)</p> <pre><code>#include &lt;fstream&gt; #include &lt;string&gt; using namespace std; ofstream out("HowMany2.out"); class HowMany2 { string name; // Object identifier static int objectCount; public: HowMany2(const string&amp; id = "") : name(id) { ++objectCount; print("HowMany2()"); } ~HowMany2() { --objectCount; print("~HowMany2()"); } // The copy-constructor: HowMany2(const HowMany2&amp; h) : name(h.name) { name += " copy"; ++objectCount; print("HowMany2(const HowMany2&amp;)"); } void print(const string&amp; msg = "") const { if(msg.size() != 0) out &lt;&lt; msg &lt;&lt; endl; out &lt;&lt; '\t' &lt;&lt; name &lt;&lt; ": " &lt;&lt; "objectCount = " &lt;&lt; objectCount &lt;&lt; endl; } }; int HowMany2::objectCount = 0; // Pass and return BY VALUE: HowMany2 f(HowMany2 x) { x.print("x argument inside f()"); out &lt;&lt; "Returning from f()" &lt;&lt; endl; return x; } int main() { HowMany2 h("h"); out &lt;&lt; "Entering f()" &lt;&lt; endl; HowMany2 h2 = f(h); } </code></pre> <p>Output </p> <pre><code>HowMany2() h: objectCount = 1 Entering f() HowMany2(const HowMany2&amp;) h copy: objectCount = 2 x argument inside f() h copy: objectCount = 2 Returning from f() HowMany2(const HowMany2&amp;) h copy copy: objectCount = 3 ~HowMany2() h copy: objectCount = 2 // Confused here !!!! why not h copy copy ~HowMany2() h copy copy: objectCount = 1 ~HowMany2() h: objectCount = 0 </code></pre>
    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. 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