lecture34-apr24 - Lecture 34 Assignment 7 Q&A; due next...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
Lecture 34 • Assignment 7 – Q&A; due next Friday • Exam #3 – Last day of class, May 8 • Topics of the day – Finish operator overloading – Inheritance Operator Overloading Example class Fred { private: int x; public: Fred (int initial_x) {x=initial_x; } // constructor int getVal ( ) {return x; } // accessor Fred operator+ {return Fred (this->x + other->x); } }; int main(void) { Fred f (3); Fred g (5); f = f + g; // treated as “f = f.operator+(g)” cout << “the new value is:” + f.getVal() << endl; return 0; } Nuances and Restrictions • The object on the left hand side of a binary operator is the calling object (i.e. this object) • You cannot alter the precedence of an operator • You cannot change the number of operands that an operator takes • Operator functions cannot have default arguments • You cannot overload . :: .* ? • You can overload new and delete if you want to implement your own special dynamic allocation scheme • Array subscripting, function calling, and class member access are defined as operators [ ], ( ), -> They can therefore be overloaded too • You can overload the comma operator , • Operator functions can be inherited by any derived class, but it can also be overloaded by the derived class (except for the = operator) Overloaded “+” Example 2 class Location /* this class represents location points on an 2D x-y grid */ { private: int xCoordinate, yCoordinate; public: Location() { } Location(int x, int y) { xCoordinate = x; yCoordinate = y; } void show() { cout << xCoordinate << " "; cout << yCoordinate << "\n"; } // define overloaded "+" operator for locations. { Location temp; temp.xCoordinate = other->xCoordinate + this->xCoordinate; temp.yCoordinate = other->yCoordinate + this->yCoordinate; return temp; } }; // end of class Location definition x y point1 point2 Using the Overloaded “+” #include <iostream> using namespace std; // class Location definition or header include goes in here // main program that uses Location int main( ) { Location point1(5, 10), point2( 10, -5), point3(0,0); point1.show( ); point2.show( ); point3 = point1 + point2;
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 3

lecture34-apr24 - Lecture 34 Assignment 7 Q&amp;A; due next...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online