WHAT IS OVERLOADING AN OPERATOR?

Can somebody explain to me what overloading an operator is, and what purpose does it serve? I've red about overloading operators for objects (e.g +, -, >>, << etc.) but i'm failing to understand the general idea behind operator overloading. Please give examples of the ++ and the >> operator in particular. Thanking you in advance.
It just means using the standard operators but redefining them to meet your specific needs. Did you read through this: http://www.cplusplus.com/doc/tutorial/classes2/
closed account (zb0S216C)
Overloading an operator means changing the way the compiler uses an operator based on its arguments. For example, say you had a vector class that stores 2 ints: X and Y. You'd overload most, if not all, of the mathematical operators to support your class. For instance:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Vector 
{
    public:
        Vector( ) : X( 0 ), Y( 0 ) 
        { }

        Vector( const int &A, const int &B )
            : X( A ), Y( B )
        { }
        
        Vector( const Vector &Ref ) 
            : X( Ref.X ), Y( Ref.Y ) 
        { }
        
    private:
        int X, Y;
        
    public:
        Vector operator + ( const Vector &Ref )
        { 
            return( Vector( ( Ref.X + this->X ), ( Ref.Y + this->Y ) ) ); 
        }
};

The overloaded operator above gives the compiler some idea how it should handle your vector. If you didn't overload the operator, the compiler won't be able to handle it; thus, you receive an error.

In a nutshell, then, an overloaded operator changes the way the compiler handles a user-defined type with a given operator.

Edit:

There's two ways you can call the operator: Implicitly or explicitly.
Implicit: Vector( 1, 2 ) + Vector( 3, 4 ).
Explicit: Vector( 1, 2 ).operator + ( Vector( 3, 4 ) ).

Wazzak
Last edited on
Topic archived. No new replies allowed.