Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't we overload "=" using friend function?

Tags:

c++

Why it is not allowed to overload "=" using friend function? I have written a small program but it is giving error.

class comp
{
int real;
int imaginary;
public:
comp(){real=0; imaginary=0;}
void show(){cout << "Real="<<real<<" Imaginary="<<imaginary<<endl;}
void set(int i,int j){real=i;imaginary=j;}
friend comp operator=(comp &op1,const comp &op2);
};

comp operator=(comp &op1,const comp &op2)
{
op1.imaginary=op2.imaginary;
op1.real=op2.real;
return op1;
}

int main()
{
comp a,b;
a.set(10,20);
b=a;
b.show();
return 0;
}

The compilation gives the following error :-

[root@dogmatix stackoverflow]# g++ prog4.cpp 
prog4.cpp:11: error: ‘comp operator=(comp&, const comp&)’ must be a nonstatic member function
prog4.cpp:14: error: ‘comp operator=(comp&, const comp&)’ must be a nonstatic member function
prog4.cpp: In function ‘int main()’:
prog4.cpp:25: error: ambiguous overload for ‘operator=’ in ‘b = a’
prog4.cpp:4: note: candidates are: comp& comp::operator=(const comp&)
prog4.cpp:14: note:                 comp operator=(comp&, const comp&)
like image 390
Ashish Avatar asked May 19 '10 11:05

Ashish


1 Answers

Because if you do not declare it as a class member compiler will make one up for you and it will introduce ambiguity.

like image 142
Michael Krelin - hacker Avatar answered Oct 14 '22 18:10

Michael Krelin - hacker