The goal of operator overloading is
2011
The goal of operator overloading is
Answer: A. to help the user of a class — Concept: Operator overloading is compile-time (static) polymorphism — a class supplies its own definition for a built-in operator symbol so that objects of…
- A.
to help the user of a class
- B.
to help the developer of a class
- C.
to help define friend function
- D.
None of the above
Attempted by 64 students.
Show answer & explanation
Correct answer: A
Concept: Operator overloading is compile-time (static) polymorphism — a class supplies its own definition for a built-in operator symbol so that objects of that class can be combined using the same notation as built-in types. It grants no ability that an ordinary named member function could not already provide; the only thing it changes is the notation available at the point where the class is used. The operator function itself must still be written out by whoever authors the class.
Application: A class is touched at two distinct sites, and overloading has a different effect at each. At the definition site the class author writes an extra function body such as operator+, work that would not exist had the class exposed a named add() instead. At the use site the calling code holding two objects can then write c3 = c1 + c2 in place of c3 = c1.add(c2). The extra code therefore falls on whoever writes the class, while the shorter, more readable notation falls on whoever consumes it through its public interface. The purpose the feature serves is that readability at the use site — its goal is to help the user of a class.
Contrast with the other stated purposes:
to help the developer of a class — the developer is the party who pays for the feature rather than the one it serves: every overloaded operator is one more function to define, test and document, so the class becomes harder to write, not easier.
to help define friend function — the dependence runs the opposite way. When the left operand is not an object of the class, as with
operator<<for stream output, the overload must be a non-member; it is declared a friend only if it additionally needs access to the class's non-public members, and a version written entirely against the public interface needs no friendship at all. Overloading does not exist in order to produce friend functions; friend functions are occasionally used to help implement them.None of the above — a stated purpose does describe the goal of the feature, so no fallback is required.
Cross-check: apply the same reasoning to a familiar library type. std::string overloads + so that calling code can write a + b to join two strings. The implementers of std::string wrote additional code to make that possible, and every program that uses std::string writes less. The benefit lands on the consumer of the class in exactly the same way.
Result: the goal of operator overloading is to help the user of a class.