Let’s now overload some Operators
You know the operators + - * / < > += -= /= *= , …
We have already seen >> and << , which are probably the most often used ones.
You cannot define new operators, only overload existing ones… sorry, no ** for exp()!
As we have seen, operators are a very intuitive notation for what is really a function call.
For our own classes, we can define what those operators mean.
Remember our cube and cylinder classes from the previous examples? We will now define some operators for those classes. Let’s start with the assignment “=“. We want to support the following:
class cube : public body {
cube (const float, const Color *c);
virtual char* identify() const;
virtual float GetVolume() const;
virtual float GetSurface() const;
// the assignment operator
cube& operator= ( const cube & );
// the assignment operator
cube& cube::operator= (const cube& c)
if ( this == &c) return (*this) ;
Complicated? Let’s go through it step by step.
The operator overloading is probably the most often abused feature of all. If it is not entirely obvious what “+” or “*” between two object means, do not implement it! It is your responsibility that it makes sense.