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

Posted by ashish-sangwan on Stack Overflow See other posts from Stack Overflow or by ashish-sangwan
Published on 2010-05-19T11:30:48Z Indexed on 2010/05/19 11:40 UTC
Read the original article Hit count: 202

Filed under:

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&)

© Stack Overflow or respective owner

Related posts about c++