How we overload '=' operator using friend function in c++.
if not why ????????????????????
The assignment operator is a very special binary operator.
It must be a non-static member function and cannot be inherited.
It may or may not get optimized away.
Meanwhile, its one of those *functions* the compiler must generate
when needed but not user-supplied.
Thats not trivial complexity for the compiler writer.
Note the output below:
#include <iostream>
class Test
{
int n;
public:
// ctor
Test(int n_) : n(n_) { std::cout << "Test(int)\n"; }
// copy ctor
Test(const Test& copy)
{
std::cout << "copy ctor\n";
n = copy.n;
}
// op=
Test& operator=(const Test& rhs)
{
if(&rhs == this) // self check!
return *this;
// do stuff
std::cout << "op=\n";
n = rhs.n;
return *this;
}
// accessor
int getn() const
{
return n;
}
};
int main()
{
Test instance(99);
Test another = instance; // not an assignment
instance = instance; // skipped, self assignment
Test test = 88; // not an assignment
std::cout << instance.getn() << std::endl;
std::cout << another.getn() << std::endl;
std::cout << test.getn() << std::endl;
}
/*
Test(int) // construction
copy ctor // copy construction
Test(int) // construction
99
99
88
*/
Not once was op= processed.
None of the statements above constitute an assignment.
Care to explain how you would have a non-member friend function handle
those special cases?