Lab 2: PolymorphismOne Name, Many PurposesTwo forms:Function OverloadingOperator Overloading
Lab 2: Polymorphism One Name, Many Purposes Two forms: Function Overloading Operator Overloading
Function OverloadingTwo or more functions can share thesame name provided that:Type of their arguments differsORNumber of their arguments differsTo overload a function, simply declare anddefine all reguired versions
Function Overloading Two or more functions can share the same name provided that: Type of their arguments differs OR Number of their arguments differs To overload a function, simply declare and define all required versions
Exampe: abs()int abs(int n) (return n < 0 ? -n : n;)long abs(long n) (return n < 0 ?-n : n;)double abs(double n) (return n < 0 ? -n : n;)int main() (cout<<"Abs. value of -10:" << abs(-10) << "ln"cout<<"Abs. value of -10L:" << abs(-10L) <<"ln";cout<<"Abs. value of -10.1:" << abs(-10.1) <<"ln";return O;^
Exampe: abs() int abs(int n) {return n < 0 ? –n : n;} long abs(long n) {return n < 0 ? –n : n;} double abs(double n) {return n < 0 ? –n : n;} int main() { cout<<“Abs. value of –10:” << abs(-10) << “\n”; cout<<“Abs. value of –10L:” << abs(-10L) <<“\n”; cout<<“Abs. value of –10.1:” << abs(-10.1) <<“\n”; return 0; }
Operator OverloadingOperator overloading is just a type offunction overloading.An operator is always overloaded relativeto a user-defined type, such as a class.To overload an operator, you create anoperatorfunction
Operator Overloading Operator overloading is just a type of function overloading. An operator is always overloaded relative to a user-defined type, such as a class. To overload an operator, you create an operator function
Member Operator functionAn operator function is often a member ofthe class for which it is defined.Syntax:return-type class-name::operator#(arg-list){// operation to be performed人
Member Operator function An operator function is often a member of the class for which it is defined. Syntax: return-type class-name::operator#(arg-list) { // operation to be performed }