Skip to content
UoL CS Notes

C++ Overloading Continued & Templates

COMP282 Lectures

Overloading

Types of Operators

There are three types of operator in C++:

  • Prefix Unary - --counter
  • Postfix Unary - counter++
  • Binary - num1 - num2

Unary Operators

To overload prefix unary operators we write:

returntype operator-();

This will override -.

To overload postfix unary operators we write:

returntype operator++(int);

The int type only means that we are defining the postfix version instead of the prefix one.

Binary Operators

To overload a binary operator we can do the following:

returntype operator+(righthandtype& r);

Friends

A friends declaration appears in a class body and grants a function, or another class, access to private and protected members of the class where the friend declaration appears.

Friendship is only one-way and is not inherited.

Redefining << for cout

To print our ruler objects we need to override << from ostream so that it knows how to output the type.

To start define the function in the class:

friend std::ostream& operator<<(std:ostream& output, const Ruler& ru);

We can then define that function elsewhere:

std::ostream& operator<<(std::ostream& output, const Ruler& ru) {
	output << ru.feet << "'" << ru.inches << '"';
	return output;
}

We can do a similar thing for overriding >>.

There will be additional examples of this in the labs.

Templates

Consider that we want to write a function to compare many different types of classes. Instead of writing many functions to do this, we can write one function to rule them all:

template <class T>
bool compare(T& t1, T& t2) {
	return t1 < t2;
}

We can then use this template like so:

compare<Ruler>(r1, r2);
compare<string>(s1, s2);

You can also make templates that take multiple classes:

template <class T, class U>
bool compare(T& t1, U& u2) {
	return t1 < u2;
}

Class Templates

To return two different objects from a single function we can use a class template:

template <class T, class U>
class TwoObjects {
	public
	T first;
	U second;
	TwoObjects(T f, U s) : first(f), second(s) {}
}
TwoObjects<Animal, int> method();

This is implemented by Pair in the standard template library.