What Is Operator Overloading

2y ago
12 Views
2 Downloads
860.56 KB
28 Pages
Last View : 1m ago
Last Download : 3m ago
Upload by : Gideon Hoey
Transcription

CH-8 Operator Overloading Overloading Unary operatorsOverloading Binary operatorsData ConversionGuidelines for overloading and conversionKeywords explicit and mutableWhat is operatoroverloading1

Overloading OperatorOperator overloading is a very neat feature of objectoriented programming Operator overloading allows programmers to givenormal C operators such as ,-, , additionalmeanings It makes statements more intuitive and readable For example: in case of disance class objectsconsider these statements.d3.addobjects(d1,d2); Ord3 d1.addobjects(d2);// can be written with the operator asd3 d1 d2 Operator Overloading The name of an operator function is the keywordoperator followed by the operator itself.void operator (){ count; }//increment (prefix)2

Overloading UnaryOperator ( , --)Overloading Unary Operator Unary operators act on only one operand. (An operand issimply a variable acted on by an operator.)Examples of unary operators are the increment anddecrement operators and --.In the COUNTER example in Chapter 6, we created aclass Counter to keep track of a count.Objects of that class were incremented by calling amember function:c1.inc count();That did the job, but the listing would have been morereadable if we could have used the increment operator instead: c1;3

Overloading Unary Operatorsclass Counter{private:unsigned int count;public:Counter() : count(0){ }unsigned int get count(){ return count; }void operator (){ count; }//count//constructor//return count//increment (prefix)};Overloading Unary Operatorsint main(){Counter c1, c2;//define and initializecout "\nc1 " c1.get count(); //displaycout "\nc2 " c2.get count(); c1; c2; c2; c2;//increment c1//increment c2//increment c2cout "\nc1 " c1.get count(); //display againcout "\nc2 " c2.get count() endl;getche();return 0;}4

Overloading Unary Operatorscounter operator () //increment count{ count;//increment countCounter temp;//make a temporary Countertemp.count count; //give it same value as this objreturn temp;//return the copy}Instead ofvoid operator (){ count; }Now we can use expressions, such asc2 c1;In main.Overloading Unary Operatorsclass Counter{ private:unsigned int count;//countpublic:Counter() : count(0) //constructor{ }Counter(int c) : count(c) //constructor, one arg{ }unsigned int get count() //return count{ return count; }Counter operator ()//increment count{ count;// increment count, then returnreturn Counter(count); // an unnamed temporary object}// initialized to this count};5

Overloading Unary OperatorPrefix vs postfix form So far we have used c1 or c2 c1 What about c1 (Postfix form) In order to use postfix form .it must be defined inside theclassCounter operator () //increment count (prefix){//increment count, then returnreturn Counter( count); //an unnamed temporary object}//initialized to this countCounter operator (int) //increment count (postfix){//return an unnamed temporaryreturn Counter(count ); //object initialized to this} Overloading Binaryoperator ( )6

Overloading Binary Operator Binary operators can be overloaded just as easily asunary operators.We’ll look at examples that overload arithmetic operators,comparison operators, and arithmetic assignmentoperators.In Chapter 6, we showed how two Distance objects couldbe added using a member function add dist():dist3.add dist(dist1, dist2);By overloading the operator we can reduce this denselooking expression todist3 dist1 dist2;Overloading Binary Operatorsclass Distance//English Distance class{ private:int feet; float inches;public://constructor (no args)Distance() : feet(0), inches(0.0){ }//constructor (two args)Distance(int ft, float in) : feet(ft), inches(in){ }void getdist()//get length from user{cout "\nEnter feet: "; cin feet;cout "Enter inches: "; cin inches; }void showdist() const//display distance{ cout feet "\'-" inches '\"'; }Distance operator ( Distance ) const; //add 2 distances};7

Overloading Binary OperatorsDistance Distance::operator (Distance d2) const //return sum{int f feet d2.feet;//add the feetfloat i inches d2.inches; //add the inchesif(i 12.0)//if total exceeds 12.0,{//then decrease inchesi - 12.0;//by 12.0 andf ;//increase feet by 1}//return a temporary Distancereturn Distance(f,i);//initialized to sum}Overloading Binary Operatorsint main(){ Distance dist1, dist3, dist4; //define distancesdist1.getdist();//get dist1 from userDistance dist2(11, 6.25);//define, initialize dist2dist3 dist1 dist2;//single ‘ ’ operatordist4 dist1 dist2 dist3; //multiple ‘ ’ operators //displayall lengthscoutcoutcoutcout "dist1"dist2"dist3"dist4 ";";";";dist1.showdist(); coutdist2.showdist(); coutdist3.showdist(); coutdist4.showdist(); cout endl;endl;endl;endl;getche();return 0;}8

Overloadingcomparison operator( )Overloading Binary Operatorsclass Distance//English Distance class{ private:int feet; float inches;public://constructor (no args)Distance() : feet(0), inches(0.0){ }//constructor (two args)Distance(int ft, float in) : feet(ft), inches(in){ }void getdist()//get length from user{cout "\nEnter feet: "; cin feet;cout "Enter inches: "; cin inches; }void showdist() const//display distance{ cout feet "\'-" inches '\"'; }bool operator (Distance) const; //compare distances};9

Overloading Binary Operator In this example we’ll overload the less than operator ( ) inthe Distance class so that we can compare two distances.bool Distance::operator (Distance d2) const //return the sum{float bf1 feet inches/12;float bf2 d2.feet d2.inches/12;return (bf1 bf2) ? true : false;}Overloading Binary Operatorsint main(){Distance dist1;//define Distance dist1dist1.getdist();//get dist1 from userDistance dist2(6, 2.5);//define and initialize dist2//display distancescout "\ndist1 "; dist1.showdist();cout "\ndist2 "; dist2.showdist();if( dist1 dist2 )//overloaded ‘ ’ operatorcout "\ndist1 is less than dist2";elsecout "\ndist1 is greater than dist2";cout endl;getche();return 0;}10

Overloading ArithmeticAssignment operator( )Overloading Binary Operator In this example we will explore the overloading of arithmeticassignment operator: the operator.This operator combines assignment and addition into onestep.We’ll use this operator to add one English distance to asecond, leaving the result in the first.E.g. d2 d1;//d2 d2 d111

Overloading Binary Operatorsclass Distance//English Distance class{ private:int feet; float inches;public://constructor (no args)Distance() : feet(0), inches(0.0){ }//constructor (two args)Distance(int ft, float in) : feet(ft), inches(in){ }void getdist()//get length from user{cout "\nEnter feet: "; cin feet;cout "Enter inches: "; cin inches; }void showdist() const//display distance{ cout feet "\'-" inches '\"'; }void operator ( Distance ); //compare distances};Overloading Binary Operatorsvoid Distance::operator (Distance d2){feet d2.feet;//add the feetinches d2.inches;//add the inchesif(inches 12.0)//if total exceeds 12.0,{//then decrease inchesinches - 12.0;//by 12.0 andfeet ;//increase feet}//by 1}12

Overloading Binary Operatorsint main(){ Distance dist1;//define dist1dist1.getdist();//get dist1 from usercout "\ndist1 "; dist1.showdist();Distance dist2(11, 6.25);//define, initialize dist2cout "\ndist2 "; dist2.showdist();dist1 dist2;//dist1 dist1 dist2cout "\nAfter addition,";cout "\ndist1 "; dist1.showdist();cout endl;getche();return 0;}Data Conversion13

Conversions b/w basic types For int var1; float var2;If we write var1(int) var2 (float); Compiler calls a special routine and convert the float into int and stores thevalue in var1.There are many such conversions: float to int, float to double, char tofloat etc.Each conversion has its own routineSuch conversions are called implicit conversions because they are notapparent.Sometimes we want to force the compiler to convert fromone type to another. To do this we use the cast operatorintvar static cast int (floatvar); This type of conversions are called explicit conversions because it isobvious.However explicit conversions also use the same built in routines of thecompiler.Conversions b/w objects andbasic types When we want to convert between user-defined data typesand basic types, we can’t rely on built-in conversionroutines, since the compiler doesn’t know anything aboutuser-defined types besides what we tell it.Instead, we must write these routines ourselves.Our next example shows how to convert between a basictype and a user-defined type.In this example the user-defined type is the Distance classfrom previous examples (feet and inches), and the basictype is float, which we use to represent meters.14

Conversions b/w objects andbasic typesclass Distance//English Distance class{ private:int feet; float inches; const float MTF; //meter to feetpublic://constructor (no args)Distance() : feet(0), inches(0.0), MTF(3.280833F){ }//constructor (one arg) to convert from basic type (float metershere) to user defined type (Distance)Distance(float meters) : MTF(3.280833F){//convert meters to Distancefloat fltfeet MTF * meters; //convert to float feetfeet int(fltfeet);//feet is integer partinches 12*(fltfeet-feet); //inches is what’s left}Conversions b/w objects andbasic typesDistance(int ft, float in) : feet(ft), inches(in), MTF(3.280833F){ }void getdist()//get length from user{cout "\nEnter feet: "; cin feet;cout "Enter inches: "; cin inches; }void showdist() const//display distance{ cout feet "\'-" inches '\"'; }// conversion operator to convert from user define type (distanceobject) to basic type.float hereoperator float() const //conversion operator{//converts Distance to metersfloat fracfeet inches/12;//convert the inchesfracfeet static cast float (feet); //add the feetreturn fracfeet/MTF;//convert to meters}};15

Conversions b/w objects andbasic typesint main(){ float mtrs;Distance dist1 2.35F;//uses 1-arg constructor to//convert meters to Distancecout "\ndist1 "; dist1.showdist();mtrs static cast float (dist1); //uses conversion operator//for Distance to meterscout "\ndist1 " mtrs " meters\n";Distance dist2(5, 10.25);//uses 2-arg constructormtrs dist2;//also uses conversion op implicitcout "\ndist2 " mtrs " meters\n";//dist2 mtrs;//error, won’t convertgetche();return 0;}Conversions From Basic toUser-Defined To go from a basic type—float in this case—to a user-defined type suchas Distance, we use a constructor with one argument. These aresometimes called conversion constructors. Here’s how this constructorlooks in distance class example:Distance(float meters){float fltfeet MTF * meters;feet int(fltfeet);inches 12 * (fltfeet-feet); }This function is called when an object of type Distance is created with asingle argument.The function assumes that this argument represents meters. It convertsthe argument to feet and inches, and assigns the resulting values to theobject.Thus the conversion from meters to Distance is carried out along withthe creation of an object in the statementDistance dist1 2.35;16

Conversions From UserDefined to Basic To convert from a user-defined type to a basic type we createdsomething called a conversion operator. Here’s how this conversionoperator looks in distance class example:operator float(){float fracfeet inches/12;fracfeet float(feet);return fracfeet/MTF; }This operator takes the value of the Distance object of which it is amember, converts it to a float value representing meters, and returns thisvalue. This operator can be called with an explicit castmtrs static cast float (dist1);or with a simple assignmentmtrs dist2; Both forms convert the Distance object to its equivalent float value inmeters.Conversions b/w objects ofdifferent classes What about converting between objects of different user-definedclasses?The same two methods just shown for conversions between basic typesand user-defined types also apply to conversions between two userdefined types.That is, you can use a one-argument constructor or you can use aconversion operator.The choice depends on whether you want to put the conversion routinein the class declaration of the source object or of the destination object.For example,suppose you sayobjecta objectb;where objecta is a member of class A and objectb is a member of classB.Is the conversion routine located in class A (the destination class, sinceobjecta receives the value) or class B (the source class)?We’ll look at both cases.17

Conversions b/w objects ofdifferent classes Our example programs will convert between two ways of measuringtime: 12-hour time and 24-hour time.These methods of telling time are sometimes called civilian time andmilitary time.Our time12 class will represent civilian time, as used in digital clocks andairport flight departure displays.We’ll assume that in this context there is no need for seconds, so time12uses only hours (from 1 to 12), minutes, and an “a.m.” or “p.m.”designation.Our time24 class, which is for more exacting applications such as airnavigation, uses hours (from 00 to 23), minutes, and seconds.Table on the next slide shows the differences.Conversions b/w objects ofdifferent classes18

Routine in sourceobjectConversions b/w objects ofdifferent classes Routine in Source Object (Using Conversion operator from t24 to t12)class time12{private:bool pm;int hrs;int mins;public://true pm, false am//1 to 12//0 to 59//no-arg constructortime12() : pm(true), hrs(0), mins(0){ }//3-arg constructortime12(bool ap, int h, int m) : pm(ap), hrs(h), mins(m){ }void display() const//format: 11:59 p.m.{cout hrs ':';if(mins 10)cout '0';//extra zero for “01”cout mins ' ';string am pm pm ? "p.m." : "a.m.";cout am pm;}};19

Conversions b/w objects ofdifferent classesclass time24{private:public:int hours;//0 to 23int minutes;//0 to 59int seconds;//0 to 59//no-arg constructortime24() : hours(0), minutes(0), seconds(0){ }time24(int h, int m, int s) : //3-arg constructorhours(h), minutes(m), seconds(s){ }void display() const//format: 23:15:01{if(hours 10) cout '0';cout hours ':';if(minutes 10) cout '0';cout minutes ':';if(seconds 10) cout '0';cout seconds;}operator time12() const;//conversion operator};Conversions b/w objects ofdifferent classestime24::operator time12() const//conversion operator{int hrs24 hours;bool pm hours 12 ? false : true; //find am/pm //round secsint roundMins seconds 30 ? minutes : minutes 1;if(roundMins 60){//carry mins?roundMins 0; hrs24;if(hrs24 12 hrs24 24)//carry hrs?pm (pm true) ? false : true; //toggle am/pm}int hrs12 (hrs24 13) ? hrs24 : hrs24-12;if(hrs12 0){ hrs12 12; pm false; }//00 is 12 a.m.return time12(pm, hrs12, roundMins);}20

Conversions b/w objects ofdifferent classesint main(){int h, m, s;while(true){cout "Enter 24-hour time: \n";cout " Hours (0 to 23): "; cin h;if(h 23)//get 24-hr time from user//quit if hours 23return(1);cout " Minutes: "; cin m;cout " Seconds: "; cin s;time24 t24(h, m, s);cout "You entered: ";t24.display();//make a time24//display the time24time12 t12 t24;cout "\n12-hour time: ";t12.display();cout "\n\n";}//convert time24 to time12//display equivalent time12return 0; }Routine in destinationobject21

Conversions b/w objects ofdifferent classes Routine in destination Object (Using one arg constructor from t24 to t12)class time24{private:public:int hours;//0 to 23int minutes;//0 to 59int seconds;//0 to 59//no-arg constructortime24() : hours(0), minutes(0), seconds(0){ }//3-arg constructortime24(int h, int m, int s) : hours(h), minutes(m), seconds(s){ }void display() const//format: 23:15:01{if(hours 10) cout '0';cout hours ':';if(minutes 10) cout '0';cout minutes ':';if(seconds 10) cout '0';cout seconds;}int getHrs() const { return hours; }int getMins() const { return minutes; }int getSecs() const { return seconds; }};Conversions b/w objects ofdifferent classes Routine in destination Object (Using one arg constructor from t24 to t12)class time12{private:bool pm;int hrs;int mins;public://true pm, false am//1 to 12//0 to 59//no-arg constructortime12() : pm(true), hrs(0), mins(0){ }time12(time24);//1-arg constructortime12(bool ap, int h, int m) : pm(ap), hrs(h), mins(m) //3-arg constructor{ }void display() const//format: 11:59 p.m.{cout hrs ':';if(mins 10)cout '0';//extra zero for “01”cout mins ' ';string am pm pm ? "p.m." : "a.m.";cout am pm;}};22

Conversions b/w objects ofdifferent classestime12::time12( time24 t24 )//1-arg constructor{//converts time24 to time12int hrs24 t24.getHrs();//get hours//find am/pmpm t24.getHrs() 12 ? false : true;mins (t24.getSecs() 30) ? //round secst24.getMins() : t24.getMins() 1;if(mins 60)//carry mins?{mins 0; hrs24;if(hrs24 12 hrs24 24)//carry hrs?pm (pm true) ? false : true; //toggle am/pmhrs (hrs24 13) ? hrs24 : hrs24-12; //convert hrsif(hrs 0)}//00 is 12 a.m.{ hrs 12; pm false; }}Conversions b/w objects ofdifferent classesint main(){int h, m, s;while(true){cout "Enter 24-hour time: \n";cout " Hours (0 to 23): "; cin h;if(h 23)//get 24-hr time from user//quit if hours 23return(1);cout " Minutes: "; cin m;cout " Seconds: "; cin s;time24 t24(h, m, s);cout "You entered: ";t24.display();//make a time24//display the time24time12 t12 t24;cout "\n12-hour time: ";t12.display();//convert time24 to time12//display equivalent time12cout "\n\n";}return 0; }23

Conversion summaryGuidelines foroverloading andconversion24

Guidelines for overloading andconversion Use Similar meanings Use overloaded operators to perform operations that are as similaras possible to those performed on basic data types.You could overload the sign to perform subtraction, for example,but that would hardly make your listings more comprehensible.Use Similar Syntax Use overloaded operators in the same way you use basic types. Forexample, if alpha and beta are basic types, the assignment operatorin the statementalpha beta;sets alpha to the sum of alpha and beta.Any overloaded version of this operator should do somethinganalogous.It should probably do the same thing asalpha alpha beta;where the is overloaded.Guidelines for overloading andconversion Show Restraint If the number of overloaded operators grows too large, and if theoperators are used in nonintuitive ways, the whole point of usingthem is lost, and reading the listing becomes harder instead ofeasier.Use overloaded operators sparingly, and only when the usage isobvious. When in doubt, use a function instead of an overloadedoperator, since a function name can state its own purpose.Avoid Ambiguity Suppose you use both a one-argument constructor and a conversionoperator to perform the same conversion (time24 to time12, forexample). How will the compiler know which conversion to use? Itwon’t.The compiler does not like to be placed in a situation where it doesn’tknow what to do, and it will signal an error.So avoid doing the same conversion in more than one way.25

Guidelines for overloading andconversion Not All operators can be overloaded The following operators cannot be overloaded:The member access or dot operator (.),The scope resolution operator (::),The conditional operator (?:),The pointer-to-member operator (- ).You can’t create new operators (like *&) and try tooverload them.Only existing operators can be overloaded.Keywords explicit andmutable26

Keyword explicit There may be some situations where you don’t want the conversions tohappen.You should actively discourage any conversion that you don’t want. Thisprevents unpleasant surprises.It’s easy to prevent a conversion performed by a conversion operator:just don’t define the operator.However, things aren’t so easy with constructors. You may want toconstruct objects using a single value of another type, but you may notwant the implicit conversions a one argument constructor makespossible in other situations.Standard C includes a keyword, explicit, to solve this problem. It’splaced just before the declaration of a one-argument constructor.explicit Distance(float meters) : MTF(3.280833F){}Distance dist1(2.35F); //explicit conversion allowedDistance dist1 2.35F; //ERROR if constructor is explicitKeyword mutable Ordinarily, when you create a const object, you want aguarantee that none of its member data can be changed.However, a situation occasionally arises where you want tocreate const objects that have some specific member dataitem that needs to be modified despite the object’sconstantness.Class scrollbar {private:int size;//related to constnessmutable string owner;//not relevant to constness }Now in Mainconst scrollbar sbar(60, “Window1”);// sbar.setSize(100);//can’t do this to const objsbar.setOwner(“Window2”);//this is OK27

28

2 Overloading Operator Operator overloading is a very neat feature of object oriented programming Operator overloading allows programmers to give normal C operators such as ,-, , additional meanings It makes statements more intuitive and readable For example: in case of disance class obje

Related Documents:

Axle Weighing & Overloading Guide . This guide provides you with information about technical terms and relevant aspects of the overloading of goods vehicles regulation. Why does overloading matter so much? 1. ROAD SAFETY: Lorries which are

Apr 04, 2020 · and objects, constructor , parameterized constructor Object instantiation Constructors Methods (defining & Calling) Types of constructor Parameter passing to methods Turn-02 3 Method overloading, constructor overloading Method overloading Constructor overloading

members of a class, data & function members. Characteristics of OOP- Data hiding, Encapsulation, data security. III Operator overloading: Fundamentals, Restrictions, operator functions as class members v/s as friend functions. Overloading stream function, binary operators and unary operators. Converting between types. IV

Automatic Differentiation of Mathematical Functions in MATLAB MATTHEW J. WEINSTEIN and ANIL V. RAO, University of Florida A source transformation via operator overloading method is presented for computing derivatives of math-ematical functions defined by MATLAB computer programs. The transformed derivative code that results

Modules Simple module Operator overloading More modules Faster programs Exercises (2) More modules Exercises (3) Fortran 2003 List of Topics 1 Modules 2 A simple module 3 Modules and Operator Overloading 4 Modules and more modules 5 Making programs run faster 6 Exercises part 2 7 More about modules 8 Exercises part 3 9 The promise of Fortran 2003 Wollan Introductory Fortran Programming, Part II

data types is performed using overloaded constructor functions. Again this reduces the number of over-loaded functions. (c) The approach is conservative and only allows overloading if no ambiguity is present, in order to not introduce pitfalls into th

- Operator Overloading including Unary and Binary Operators, Function Overloading 4. Runtime Polymorphism - Inheritance ,Virtual functions - Virtual Base Classes, Templates - File Handling-Sequential access, Random access. BCS3L2 OBJECT ORIENTED PROGRAMMING LAB

Std. XII : Commerce Adjustments for Reserve Fund, Partner’s Loan Account, Asset taken over by Partner and Contingent Liability *Q.5. A, B and C were partners sharing profits and losses in the ratio of 3 : 2 : 1. On 31st March, 2010, their Balance Sheet was as follows: Balance Sheet as on 31st March, 2010 Liabilities Amount Assets Amount Sundry Creditors 15400 Cash at Bank 3,500 Bills .