Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use the = operator to assign one object's values to another object, without overloading the operator?

Tags:

c++

this was a recent T/F question that came up in my cs course that I found a bit confusing.

The textbook states:

The = operator may be used to assign one object's data to another object, or to initialize one object with another object's data. By default, each member of one object is copied to its counterpart in the other object.

The question verbatim was:

You cannot use the = operator to assign one object's values to another object, unless you overload the operator. T/F?

Judging from that particular paragraph of the textbook, I answered false. However, it turns out the quiz answer was actually true.

When I looked up the question online, I saw other sources listing the answer as "false" as well. Granted, these were just generic flashcard / quiz websites, so I don't put much stock in them.

Basically, I'm just curious what the real answer is for future studying purposes.


P.S.: The textbook later goes on to state: "In order to change the way the assignment operator works, it must be overloaded. Operator overloading permits you to redefine an existing operator’s behavior when used with a class object."

I feel like this is related and supports the "true" answer, but I'm not really sure.

like image 245
Random Coder Avatar asked Sep 29 '16 05:09

Random Coder


2 Answers

The statement

You cannot use the = operator to assign one object's values to another object, unless you overload the operator.

… is trivially false, because you can assign to e.g. an int variable. Which is an object. In C++.

Possibly they intended to write “class-type object”, but even so it's false. E.g. any POD (Plain Old Data) class type object is assignable and lacks an overloaded assignment operator.

However, there are cases where you want or need to prohibit or take charge of assignment.

like image 120
Cheers and hth. - Alf Avatar answered Sep 27 '22 22:09

Cheers and hth. - Alf


If you don't implement the assignment operator yourself, the compiler will generate one for you, which will copy the data from the source to the destination, invoking assignment operators of the members of your class where possible/necessary.

This does not work if your class e.g. features const members, and it does not yield the desired result if your class contains pointers to dynamically allocated objects.

So, I would also say that the statement is false.

like image 33
Rene Avatar answered Sep 28 '22 00:09

Rene