Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing conversion constructor implicitly requires copy constructor
    primarykey
    data
    text
    <p>Im learning C++ and I ran into something strange that I couldn't find any info on in my C++ book, or on the web. The code below is simply a test of the conversion constructor: Test(int). testFunction gets an int where a Test object is expected, and the conversion constructor is used to create a Test object to send to the function. This works as expected. </p> <pre><code>#include &lt;iostream&gt; using namespace std; class subClass { public: subClass(int); subClass(subClass&amp;); }; subClass::subClass(int i) {}; subClass::subClass(subClass&amp; i) {}; class Test { public: Test(const Test&amp;); Test(int); subClass sub; }; Test::Test(const Test &amp;) : sub(1) {}; Test::Test(int in) : sub(1) {}; void testFunction(Test in) { cout &lt;&lt; "testfunction\n"; }; int main () { testFunction(4); } </code></pre> <p>However, If i remove the copy constructor Test(const Test&amp;) from the Test class I get the error message shown below. But the copy constructor is never used, so why is it needed? </p> <pre><code>example.cpp: In function `int main()': example.cpp:32: error: no matching function for call to `Test::Test(Test)' example.cpp:13: note: candidates are: Test::Test(Test&amp;) example.cpp:24: note: Test::Test(int) example.cpp:32: error: initializing argument 1 of `void testFunction(Test)' from result of `Test::Test(int)' </code></pre> <p>Additional info: I noticed that either removing the copy constructor from the subclass or passing the argument by reference to testFunction makes it possible to compile the function without Test's copy constructor. Im using the gnu g++ compiler in cygwin. </p>
    singulars
    1. This table or related slice is empty.
    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.
    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