You are on page 1of 6

More about

Classes
COS110: Chapter 14
Dr. Mard Helbig

Overloading Prefix ++ Operator


Unary operator
Only affects object calling the operator
No need for a parameter
++ exists for primitive types, e.g. int x=4; int y = ++x;
++x is similar than calling x.operator++();

Prefix ++ operator first increments value and then


uses the value

Overloading Prefix ++ Operator


class Wizard
{
private:
int age;
public:
Wizard operator++ ();
};
Wizard Wizard::operator =++()
{
++age;
return *this;
}

Allows operator to work


correctly for cases such as:
wizard2 = ++wizard1;

Overloading Postfix ++ Operator


But how will the compiler whether I am referring to
the prefix ++ operator or the postfix ++ operator?
E.g. do I mean ++x or x++
Postfix first uses the value and then increments it
Otherwise, similar to prefix ++ operator
Does not need an argument

Overloading Postfix ++ Operator


Dummy parameter only
indicates to compiler that it
is the postfix ++ operator

class Wizard
{
private:
int age;
public:
Wizard operator++ (int);
};

Cannot use *this as return


argument. Why?

Wizard Wizard::operator =++(int)


{
Wizard temp(name, age, spells);
age++;
return temp;
}
Return the
unchanged age
value

Creates a new wizard with


the data values of the
current object before
incrementing the value

Example
Code

Change value of current


objects age, but temps age
remains unchanged

Overloading Relational
Operators
Implemented similar to other binary operators (e.g.
+)
But returns a true or false value
Overloading relational operators enable us to
define how to compare 2 objects of our class
If we overloaded both > operator and == operator,
can we use >= operator with correct results for our
class?
Example
Code