GeeksforGeeks » C/C++ Programming Questions

C++ operator overloading question

(3 posts)

Tags:

  1. geek
    guest
    Posted 1 year ago #

    Why certain operators can not be overloaded?

  2. appapurapu
    Member
    Posted 1 year ago #

    Never overload &&, ||, or , .
    Reason:
    Because short circuit semantics(it evaluates its arguments in left-to-right order) will replace with function call semantics.
    For example, if you overload &&, then the
    if( exp1 && exp2) looks like below
    Case1: When operator&& is a member function ==> if(exp1.operator&&(exp2))
    Case2: When operator&& is a global function ==> if(operator&&(exp1, exp2))
    First, When function call is made, all parameters must be evaluated. ==> no short circuit.
    Second, The language specification leaves undefined the order of evaluation of parameters to a function call, so there is no way to know whether exp1 or exp2 will be evaluated first.

    As a result, never overload &&, ||, . operators.

  3. Misraji
    Member
    Posted 1 year ago #

    I think the question refers to the operators: Scope operator (::), Access Operator (.), Ternary Operator(? :) and (.*).
    These are the ones that cannot be overloaded as opposed to should not be overloaded.

    But the above answer is a nice one too. Thanks

    ~Ashish


Reply

You must log in to post.

RSS feed for this topic