Error in automatic conversion

class Sample { public: Sample(); Sample(int i); Sample(Sample& s); ~Sample(); }; Sample::Sample() { cout<<"Default constructor called\n"; } Sample::Sample(int i) { cout<<"1-argument constructor called\n"; } Sample::Sample(Sample& s) { cout<<"Copy constructor called\n"; } Sample::~Sample() { cout<<"Destructor called\n"; } void Fun(Sample s) { } int main() { Sample s1; Fun(5); return 0; } 

I was expecting an implicit conversion of 5. But, when I compile the above code, I get the following error:

 main.cpp:7:8: error: no matching function for call to 'Sample::Sample(Sample)' main.cpp:7:8: note: candidates are: Sample.h:10:3: note: Sample::Sample(Sample&) Sample.h:10:3: note: no known conversion for argument 1 from 'Sample' to 'Sample&' Sample.h:9:3: note: Sample::Sample(int) Sample.h:9:3: note: no known conversion for argument 1 from 'Sample' to 'int' Sample.h:8:3: note: Sample::Sample() Sample.h:8:3: note: candidate expects 0 arguments, 1 provided Helper.h:6:13: error: initializing argument 1 of 'void Fun(Sample)' 

What is the problem? When I remove the copy constructor, the above code compiles successfully.

Thanks in advance.

+4
source share
1 answer

Temporary users cannot communicate with non-constant links. Your copy constructor should be:

 Sample::Sample(const Sample&) 

Deleting this file causes the compiler to generate a trivial one that will have the above signature.

+6
source

All Articles