Lec14OperatorOverloading_2per.pdf - The University Of...

Info icon This preview shows pages 1–5. Sign up to view the full content.

1 The University Of Michigan Andrew M. Morgan EECS402 Lecture 14 Savitch Ch. 8 Operator Overloading Returning By Constant Value EECS 402 EECS 402 Andrew M Morgan 2 Consider This Program class ChangePocketClass { public: ChangePocketClass():quarters(0),dimes(0) {} ChangePocketClass(int q, int d): quarters(q), dimes(d) {} void setQuarters(int val) { quarters = val; } void setDimes(int val) { dimes = val; } int getQuarters() { return (quarters); } int getDimes() { return dimes; } private: int quarters; int dimes; }; From main: ChangePocketClass c1; ChangePocketClass c2; ChangePocketClass c3; c1.setQuarters(5); c1.setDimes(7); c2.setQuarters(3); c2.setDimes(8); c3 = c1 + c2;
Image of page 1

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

2 EECS 402 EECS 402 Andrew M Morgan 3 Program Discussion What does the line "c3 = c1 + c2;" do? Logically, you would expect it to add the number of quarters in the c1 object to the number of quarters in the c2 object, and add the dimes as well Would you expect that adding two objects of any class works this way? (A member-by-member addition?) No For example, adding two "PersonClass" objects together doesn't make sense Due to this, addition is not provided by default for user-defined classes Therefore, the compiler will not allow the addition (yet) EECS 402 EECS 402 Andrew M Morgan 4 Using Operators While the operator "+" makes perfect sense for types such as int and float, what does it mean for user-defined data types? The programmer must define it, and implement it when appropriate Often, it doesn’t make any sense to perform mathematical operations on user-defined class types Rather than use the "+" operator, programmer could write a member function named "add": ChangePocketClass ChangePocketClass::add(const ChangePocketClass &rhs) const; Users aren't used to writing "c3 = c1.add(c2);" to add two items "c3 = c1 + c2;" would make a lot more sense, and wouldn't require a user to look up a function prototype to determine how to add two objects together
Image of page 2