Lab 10: Operator Overloading
Topics
- Container Classes
- Generic Programming
- Operator Overloading
Container Classes
Container Classes are classes that maintain collections of objects.
Example:
class PersonContainer { public: ... private: Person* array; ... }
The operations on container classes can be:
- member functions of the container class
- global functions that take a container argument
Three concepts of container class implementation:
- the kind of container (e.g., list-based, array-based)
- the kind of objects stored in the container (e.g., Person, int)
- the kind of operations on the elements stored in the container (i.e., "do something for each element")
Usually, there is a strong coupling between the three concepts.
Generic Programming
Generic programming is a method through which we can remove (or greatly reduce) the strong coupling between containers, container elements and operations on the elements of the container.
Generic Programming is to program with types as parameters.
We will learn more on this in the next lab.
Operator Overloading
A few points to be noted:
- After operator overloading, we can use operators with objects
- Almost all operators in C++ can be overloaded. Four exceptions:
. :: ?: sizeof - We can only redefine existing operators, but CANNOT define new operators
- We CANNOT change the properties of an operator. (Number of arguments an operator takes, associativity and precedence).
Lab Task
Here is a class Array with boundary checking in Array.h, Array.cpp and main.cpp. It is a type-generic array, where type T is currently defined as int. The class is already almost implemented for you, but most codes are poorly organized such that the implementation part is mixed with the declaration part. Your tasks in this lab are
- Implement the operator overloading for the operators =,== and [] declared in Array.h and put them in Array.cpp, where the meanings of the operators have been given in the files.
- In order to merge two string arrays together in merge.cpp, please implement one more member function Array& operator+=(const Array& arr); which appends an Array object to the end of another Array object.
Note:
- You need to define the type T as string (instead of int) and put #include<string> in Array.h.
- After completeing both tasks, compile merge.cpp together with your Array.cpp and Array.h. The TA will check your program and codes.