Introduction to Operators

We use operators all the time in C++. A few examples:

     A = B + C % 2;
     G = H * J / K:
     cout << M;
     cin >> N;
     P = &Var;
     J++;
     H = --J;
     if (This == That)

We don't often think about what operators actually are. They tend to use funny symbols we may not use elsewhere, and they tend to have a funny notation. Mostly, though, an operator is simply a function, and we can write functions. We can write our own versions of operators to work with our own classes.

For the elementary types of variables, like int, char or float, we don't need to do this. When we have our own classes, though, it is useful to be able to write our own versions of the assignment operator, comparison operators, the insertion and extraction operators << and >> for output and input, and sometimes for arithmetic.

So what does this look like?

In general, we have a prototype statement:

     return-type operator symbol(arguments);

The return type depends on which operator is involved. So do the arguments. We will see a variety of possibilities.

We usually make each operator a method of the class involved, but it could just as easily be a stand-alone function (using access methods to work with the data members) or it could be a friend function.

In the case of the extraction and insertion operators, we usually make them friends of the class, as they cannot be members.

Most but not all of the operators in the C++ language can be redefined.