14.1. Basic Concepts

Image

Overloaded operators are functions with special names: the keyword operator followed by the symbol for the operator being defined. Like any other function, an overloaded operator has a return type, a parameter list, and a body.

An overloaded operator function has the same number of parameters as the operator has operands. A unary operator has one parameter; a binary operator has two. In a binary operator, the left-hand operand is passed to the first parameter and the right-hand operand to the second. Except for the overloaded function-call operator, operator(), an overloaded operator may not have default arguments (§ 6.5.1, p. 236).

If an operator function is a member function, the first (left-hand) operand is bound to the implicit this pointer (§ 7.1.2, p. 257). Because the first operand is implicitly bound to this, a member operator function has one less (explicit) parameter than the operator has operands.


Image Note

When an overloaded operator is a member function, this is bound to the left-hand operand. Member operator functions have one less (explicit) parameter than the number of operands.


An operator function must either be a member of a class or have at least one parameter of class type:

// error: cannot redefine the built-in operator for ints
int operator+(int, int);

This restriction means that we cannot change the meaning of an operator when applied to operands of built-in type.

We can overload most, but not all, of the operators. Table 14.1 shows whether or not an operator may be overloaded. We’ll cover overloading new and delete in § 19.1.1 (p. 820).

Table 14.1. Operators

Image

We can overload only existing operators and cannot invent new operator symbols. For example, we cannot define operator** to provide exponentiation.

Four symbols (+, -, *, and &) serve as both unary and binary operators. Either or both of these operators can be overloaded. The number of parameters determines which operator is being defined.

An overloaded operator has the same precedence and associativity (§ 4.1.2, p. 136) as the corresponding built-in operator. Regardless of the operand types

x == y + z;

is always equivalent to x == (y + z).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.181.252