Cistoran
Cistoran

Reputation: 1597

Operator Overloading in C++

So I'm in a basic programming II class. We have to create a program that makes 4 different functions that will change the way an operator works. I've looked up multiple examples and sets of text that display how to do this, but I cannot make which way of what any of the code means. To me something like this should work.

int operator++()
{
    variableA--;
}

To me, this says if you encounter a ++, then -- from the variable, now obvious it doesn't work like this. All the examples I've found create their own data type. Is there a way to overload an operator using an int or a double?

Upvotes: 0

Views: 217

Answers (3)

Cameron
Cameron

Reputation: 98746

All the examples create their own data type since this is one of the rules for operator overloading: An overloaded operator must work on at least one user-defined type.

Even if you could overload ++ for integers, the compiler wouldn't know which one to use -- your version or the regular version; it would be ambiguous.

You seem to think of operators as single functions, but each overload is a completely separate function differentiated by its function signature (type and sometimes number of arguments), while having the same operator symbol (this is the definition of "overloading").

So, you can't overload ++ to always do something different; this would really be operator overriding, which C++ doesn't allow.

You can define ++ for a type you've created though:

class MyType {
public:
    int value;
};

MyType const& operator++(MyType& m) {   // Prefix
    ++m.value;
    return m;
}

const MyType operator++(MyType& m, int) {   // Postfix (the 'int' is just to differentiate it from the prefix version)
    MyType temp = m;
    ++m.value;
    return temp;
}

int main() {
    MyType m;
    m.value = 0;
    m++;    // Not m.value++
    cout << m.value;    // Prints 1
}

Note that this set of ++ operators was defined outside of the MyType class, but could have been defined inside instead (they would gain access to non-public members that way), though their implementations would be a little different.

Upvotes: 6

You can't overload operators of built-in types. (Well, technically you can overload things like "int + MyClass" - but not when both sides are built-in types)

Upvotes: 1

Related Questions