Summary
In computer programming, operator overloading, sometimes termed operator ad hoc polymorphism, is a specific case of polymorphism, where different operators have different implementations depending on their arguments. Operator overloading is generally defined by a programming language, a programmer, or both. Operator overloading is syntactic sugar, and is used because it allows programming using notation nearer to the target domain and allows user-defined types a similar level of syntactic support as types built into a language. It is common, for example, in scientific computing, where it allows computing representations of mathematical objects to be manipulated with the same syntax as on paper. Operator overloading does not change the expressive power of a language (with functions), as it can be emulated using function calls. For example, consider variables , and of some user-defined type, such as matrices: In a language that supports operator overloading, and with the usual assumption that the '*' operator has higher precedence than the '+' operator, this is a concise way of writing: However, the former syntax reflects common mathematical usage. In this case, the addition operator is overloaded to allow addition on a user-defined type in C++: Time operator+(const Time& lhs, const Time& rhs) { Time temp = lhs; temp.seconds += rhs.seconds; temp.minutes += temp.seconds / 60; temp.seconds %= 60; temp.minutes += rhs.minutes; temp.hours += temp.minutes / 60; temp.minutes %= 60; temp.hours += rhs.hours; return temp; } Addition is a binary operation, which means it has two operands. In C++, the arguments being passed are the operands, and the object is the returned value. The operation could also be defined as a class method, replacing by the hidden argument; However, this forces the left operand to be of type : // The "const" right before the opening curly brace means that |this| is not modified. Time Time::operator+(const Time& rhs) const { Time temp = *this; // |this| should not be modified, so make a copy. temp.
About this result
This page is automatically generated and may contain information that is not correct, complete, up-to-date, or relevant to your search query. The same applies to every other page on this website. Please make sure to verify the information with EPFL's official sources.