class sample
{ int i;
public:
explicit sample(int a)
{ i=a;
cout<<"i amin constructor"<<endl;
}
sample(sample &s)
{ i=s.i;
cout<<"i am in copy constructor"<<endl;
}
void display()
{ cout<<" i am in display";
}
};
and if i write this statement in the main
sample r=sample(8);
it is throwing following error...
explicitk.cpp:31:21: error: no matching function for call to ‘sample::sample(sample)’
explicitk.cpp:31:21: note: candidate is:
explicitk.cpp:14:1: note: sample::sample(sample&)
explicitk.cpp:14:1: note: no known conversion for argument 1 from ‘sample’ to ‘sample&’
#include <iostream>
struct MyStruct
{
int a;
MyStruct():a(10){}
MyStruct( const MyStruct &other )
{
this->a = other.a;
}
};
int main( int argc, char* argv[] )
{
MyStruct firstStruct; // Runs normal constructor, a is 10
firstStruct.a = 4; // Let's change the value
MyStruct secondStruct( firstStruct ); // Copies the first struct
std::cout << "Value of a in secondStruct is " << secondStruct.a << std::endl;
return 0;
}
Yes, he's calling the custom constructor which will work. Also, using his code if he were to call the copy constructor, he shouldn't get the error he is apparently getting. If I just copy his code it all compiles and works and if I just add a further line to the main function:
The problem is that you defined the copy constructor as haveing as the parameter non-const reference to class object.
In this statement
sample r=sample(8);
at first a temporary object of type sample is created using constructor explicit sample( int ):
sample( 8 )
A temporary object can be binded with const reference. So apart from the copy constructor sample( sample & ) you need copy constructor sample( const sample &). Your code could be compiled if you would write
sample t( 8 );
sample r=t;
In this case your copy constructor would be called because t is not a temporary object.
It is enough to have only one copy constructor defined as
sample( const sample & )
It will be called for temporary and non-temporary objects.