Bitwise NOT operator

suggest change

Overloading the bitwise NOT (~) is fairly simple. Scroll down for explanation

Overloading outside of class/struct:

T operator~(T lhs)
{
    //Do operation
    return lhs;
}

Overloading inside of class/struct:

T operator~() const
{
    T t(*this);
    //Do operation
    return t;
}

Note: operator~ returns by value because it must return a new value, not a reference to a local object (that reference would dangle). Returning const T would still allow int a = ~a + 1, but it would also block moving from the result, so the return type is non-const.

Inside the class/struct, make a temporary, because operator~ must not modify *this. Mark it const.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents