H
H
HelloW2014-06-09 23:08:56
OOP
HelloW, 2014-06-09 23:08:56

OOP. Which operations are only allowed to be overloaded as class methods? And why?

Do I understand correctly that these are the operators =, [ ], ( ), -> and type casting?
Why they?
Thank you!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Misha Krinkin, 2014-06-09
@kmu1990

Maybe the point is that these operators only make sense with class objects, while others can be redefined for enums.

J
jcmvbkbc, 2014-06-10
@jcmvbkbc

C++99 Standard, chapter 13.5 Overloaded operators:

An operator function shall either be a non-static member function or be a non-member function and have at
least one parameter whose type is a class, a reference to a class, an enumeration, or a reference to an enu-
meration. It is not possible to change the precedence, grouping, or number of operands of operators. The
meaning of the operators =, (unary) &, and , (comma), predefined for each type, can be changed for spe-
cific class and enumeration types by defining operator functions that implement these operators. Operator
functions are inherited in the same manner as other base class functions

Those. all the operators you listed can be free functions. Can not. Further in the same chapter, they write about individual operators.
Why - I think that only by tradition. I see no other reason why one could not write, say,
const B& operator [] (const A& obj, int idx);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question