How can we overload '=' operator using friend function c++

M

Mahain

How we overload '=' operator using friend function in c++.
if not why ????????????????????
 
S

Salt_Peter

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?
 
J

James Kanze

How we overload '=' operator using friend function in c++.

You can't. The language requires operator= to be a member.
if not why ????????????????????

Because if it isn't declared by the user in the class
definition, the compiler declares one automatically.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top