#include<iostream>
using namespace std;
class Abc
{
public:
int a;
Abc()
{
cout<<"Def cstr called\n";
a=0;
}
Abc(Abc &source)
{
a=source.a;
cout<<"copy constructor is called"<<endl;
}
void operator = (Abc &source)
{
a=source.a;
cout<<"overloaded assignment operator"<<endl;
}
Abc display(Abc ab)
{
cout<<"The a in display "<<ab.a<<endl;
return ab;
}
};
int main()
{
Abc a;
Abc b;
a.a=10;
b=a;
cout<<"b.a ="<<b.a<<endl;
Abc x;
x = (a.display(b));
return 0;
}
In the line x = (a.display(b)) I am getting the compilation error. On commenting this line it works. Please help in modifying the program so as to compile it successfully and please suggest me what wrong is going here.
You should be passing your constructor and assignment arguments by const reference, rather than just by reference:
ie:
You may (or may not) also want display to be like this:
ASIDE: While these changes are not strictly required, they will prevent some tricky errors – one of which you’ve run into:
Here display is returning a temporary
Abc, andoperator=is taking a non-constAbcreference. One odd rule of C++ is that you can not bind a non-const reference to a temporary – hence your error.