0
Error while working with copy constructor in c++
#include <iostream> using namespace std; class cmplex { int a,b; public: cmplex(int x,int y){a=x;b=y;cout<<"its inside constructor 1"<<a<<" "<<b<<endl;} cmplex(int y){a=y;cout<<"its inside constructor 2 "<<a<<endl;} cmplex(){cout<<"its inside constructor 3"<<endl;} cmplex(cmplex &c){a=c.a;b=c.b;cout<<"its inside copy constructor 1"<<endl;cout<<a<<b<<endl;} }; int main() { cmplex c1(2,3),c2(2,33); c1=cmplex(2,3),c2=cmplex(2,33); cmplex c3=cmplex();//"cmplex c3" cmplex c4(c2); return 0; } Works fine when line no 18. is replaced with "cmplex c3;" So why is it showing error if line 18 is set "cmplex c3=cmplex();" Unable to understand the issue.Thanks
1 Answer
+ 7
Modify your last overload of the class constructor to take
const cmplex&
instead of
cmplex&
This is because assignment operator cannot take RHS of non-constant references. Similar situation:
void assn(std::string& str){}
int main()
{
assn("hello");
return 0;
}