Operator Overloading
Operator Overloading
Operator Overloading
1
Definition in the CPP File Oops
// + operator definition
Queue Queue::operator + (const Queue & rhs) {
//lhs is “this”
Queue result; // new Queue to be returned • That last definition had an error. See what
// store this.contents & rhs.contents in result it was?
for (int i = 0; i < n; i++) {
result.contents[i] =contents[i ];
}
for (int i = n; i < n + rhs.n; i++) {
result.contents[i] =rhs.contents[i-n];
}
// update size
result.n = n+rhs.n;
return result;
}
class Queue {
public:
Step 3: Assignment Operator // (regular functions go here)
// now, define that the operator will be
// overloaded. Note only one param:
• We now must define the behaviour of the …
Queue & operator = (const Queue &);
“=” operator. };
…
• We will make the intuitive choice of Queue& Queue::operator = (const Queue &rhs) {
overwriting the data on the lhs with the // make sure not copying onto itself
if (this != & rhs) {
data of the rhs //copy data from old to new
n = rhs.n;
• Add the prototype to the class (.h file) // this is the “deep copy” part
for (int i=0; i<rhs.n; i++) {
• Add the definition to the class (.cpp file) contents[i] = rhs.contents[i];
}
}
return *this;
2
Still Need To…
• Provide a destructor
• Provide a copy -constructor
• Overload other operators?