Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy this statement does not call the constructors - C++
    text
    copied!<p>A template class and a normal class:</p> <pre><code>template &lt;typename Type&gt; class Holder { public: Holder(const Type&amp; value) : held_(value) { cout &lt;&lt; "Holder(const Type&amp; value)" &lt;&lt; endl; } Type&amp; Ref() { return held_; } private: Type held_; }; class Animal { public: Animal(const Animal&amp; rhs) { cout &lt;&lt; "Animal(const Animal&amp; rhs)" &lt;&lt; endl; } Animal() { cout &lt;&lt; "Animal()" &lt;&lt; endl; } ~Animal() { cout &lt;&lt; "~Animal" &lt;&lt; endl; } void Print() const { cout &lt;&lt; "Animal::Print()" &lt;&lt; endl; } }; </code></pre> <p>Then I want to instantiate a <code>Holder&lt;Animal&gt;</code> with this statement <code>Holder&lt;Animal&gt; a(Animal());</code>, however, it fails. I mean <code>Animal()</code> is not treated as a temporary object. And this statement doesn't call <code>Holder</code>'s constructor.</p> <p>If someone could explain? I'm not clear. I'm guessing <code>a</code> becomes a type here. Then, I use <code>Holder&lt;Animal&gt; a = Holder&lt;Animal&gt;(Animal());</code>, it works well. So, there are some cases here:</p> <ol> <li><code>Holder&lt;Animal&gt; a(Animal()); a.Ref().Print(); // error</code></li> <li><code>Holder&lt;Animal&gt; a = Holder&lt;Animal&gt;(Animal()); a.Ref().Print(); // ok</code></li> <li><code>Holder&lt;int&gt; b(4); b.Ref() = 10; cout &lt;&lt; b.Ref() &lt;&lt; endl; //ok</code></li> </ol> <p>Can explain? I'm just a little confused with the first statement. And the error information this statement causes:</p> <p><code>GCC4.7.2</code>: <code>error: request for member 'Ref' in 'a', which is of non-class type 'Holder&lt;Animal&gt;(Animal (*)())'</code></p> <p><code>VS10</code>: <code>error C2228: left of '.Ref' must have class/struct/union</code>, <code>error C2228: left of '.Print' must have class/struct/union</code></p>
 

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