8 - Operator overloading, Friends, and References. Flashcards
What is the relationship between operators and functions?
Operators are nothing but functions that are used with a slightly different syntax. We write x + 7 instead of +(x, 7). But the operator is a function that takes two arguments (often called operands in this case.)
If operators basically are functions, why do they exist at all?
Operands are an example of what is often called syntactic sugar, meaning a slightly different syntax that people like.
What is syntactic sugar?
Syntactic sugar us a syntax that people like. It may differ from the rest of the syntax.
What is the syntax for the function declaration of an operator declaration?
An example is :
const Money operator + (const Money& amount1, const Money& amount 2);
One major restriction on overloading an operator is that …
at least one operand must be of a class type.
What is a binary operator?
With a binary operator, the arguments are listed before and after the operator; with a function the arguments are listed in parentheses after the function name. Examples of binary operators are: +, - , /, %, and so forth.
What is special about the return statement in a definition of an overloaded operator?
It may often return an object of a class. This can be done simply using the constructor of the class, and passing it arguments. Such as:
return Money (finalDollars, finalCents);
return Money (finalDollars, finalCents);
This object is sometimes called …
An anonymous object, since it is not named by any variable.
What is an anonymous object?
An object of a class that is not named by any variable. Can be constructed using the constructor function.
const Money operator + (……..)
This is a new use of the const modifier. What is this use called?
This is called “returning a value as const” or “ returning by const value” or “returning by constant value”.
Why would you ever want to return by const value?
It provides a kind of automatic error checking. When you construct (m1 + m2) , you normally do not want to inadvertently change it. In this case changing the object (m1 + m2) probably does not matter, but if the returned object is a reference to an existing object then this can cause problems.
With objects of a class, the default assignment operator does not …
With objects of a class, the default assignment operator (=) does not make the two objects the same objects, it only copies values of member variables from one object to another object.
Returning by const is difficult to understand. What’s a good rule of thumb for this method?
A good rule of thumb is to always return class types by const value unless you have have explicit reason not to do so.
There are two types of operators. Which?
- binary and
2 unary.
What are unary operators?
A unary operator is an operator that takes only one operand.