CSC/ECE 517 Fall 2010/ch5 5a MR: Difference between revisions
Madhubharath (talk | contribs) No edit summary |
Madhubharath (talk | contribs) No edit summary |
||
Line 3: | Line 3: | ||
=Method Overloading= | =Method Overloading= | ||
=Operator Overloading= | ='''Operator Overloading'''= | ||
The ability to define how user defined classes interact with operators applicable to primitive types is called Operator Overloading. | The ability to define how user defined classes interact with operators applicable to primitive types is called '''Operator Overloading'''. In simple words, it means that a single operator can handle multiple argument types. This will help us to prevent using functional-style syntax for manipulation. | ||
To define an overloaded operator, a function '''''operator''''' # is defined. The # represents the operator that is to be overloaded. | |||
Example: operator +, operator >> | |||
The overloading is actually done in C++ by replacing instance of every operator with the a call to the operator function. | |||
Example: int a,b,c; | |||
a = b*c; | |||
It is equivalent to - | |||
int a,b,c; | |||
a.operator = (operator+(b,c)); | |||
Some operators cannot be overloaded because of their requirement at compile-time. | |||
Examples of such operators are: | |||
* '''::''' => Scope Resolution | |||
* '''.''' => Member Selection | |||
* '''?:''' => Ternary Conditional | |||
* sizeof => Size of Object | |||
All the other operators can be overloaded. | |||
In a broad sense, operators are classified into - | |||
* Arithmetic Operators | |||
* Relational Operators | |||
* I/O Operators | |||
The operator overloading for each type follows. | |||
=='''Arithmetic Operators'''== | |||
It includes +=,-=,*=,/=,%= and their corresponding binaries are +,-,*,/,% respectively. It is easy to implement arithmetic assignment operators as member functions and using these to implement the binary operators. Usually binary operators are implemented as independent, non-member functions. The problem in making it a member function is that it requires an object to which it can be applied [1]. | |||
==='''Overloading of Arithmetic Assignment Operator'''=== | |||
Example: [1] | |||
const BigInt& BigInt::operator += (const BigInt & rhs) | |||
// post condition : rhs has to be added to *this | |||
// *this has to be returned | |||
BigInt a = Factorial(25); | |||
BigInt b = Factorial(30); | |||
Then the overloaded function is called as - | |||
a+=b; | |||
BigInt c = (b+=b); | |||
The arithmetic assignment operators should return a value. The return type should be a reference to avoid copy and it must be a constant. | |||
More information on overloading Arithmetic Assignment operators can be obtained from [1]. | |||
==='''Overloading of Binary Operator'''=== | |||
Example: [2] | |||
Let us define a class Matrix. | |||
class Matrix | |||
{ public : | |||
/* other member functions */ | |||
MATRIX &operator *= (double scalar); | |||
private : | |||
static const int MATRIX_SIZE =3; | |||
double entries[MATRIX-SIZE][MATRIX_SIZE]; | |||
}; | |||
const Matrix operator *(double scalar) const | |||
{ MyMatrix result = *this; | |||
result*=scalar; | |||
return result; | |||
} | |||
The *= operator will scale all the elements in the matrix by a ''double'' factor. The function can now be called as | |||
myMatrix = myMatrix * 2.3471; | |||
More information on overloading of binary operators can be obtained from [2]. | |||
=='''Relational Operators'''== | |||
Some of the relation operators are <,>,==,!,!=,&& which have a return type of ''bool''. | |||
The relational operator overloading functions are generally globally defined so that they can be used without any worry about the order the arguments passed. | |||
==='''Overloading of Relational Operators'''=== | |||
Example : [2] | |||
bool operator==(const Date & lhs, const Date & rhs); | |||
bool operator<(const Date &lhs, const Date & rhs); | |||
bool operator==(const Date & lhs, const Date & rhs) | |||
{ return lhs.equal(rhs); | |||
} | |||
bool operator<(const Date & lhs, const Date & rhs) | |||
{ return lhs.less(rhs); | |||
} | |||
This shows the declaration and defintion for overloading == and < operator. The function for operator == will return true if lhs is equal to rhs and false otherwise. Similarly, the function for operator < will return true if lhs is less than rhs and false otherwise. | |||
More information on overloading of Relational Operators can be obtained from [1] and [3]. | |||
=='''I/O Operators'''== | |||
Some examples of I/O Operators are << and >> i.e the ostream and istream operators. Both the operators are left-associated, meaning they evaluate the expression from left to right like, | |||
(((cout<<1)<<2)<<endl); [2] | |||
==='''Overloading of I/O Operators'''=== | |||
Example : [2] | |||
ostream&operator<<(ostream & out, const BigInt & big) | |||
{ out<<big.tostring(); | |||
return out; | |||
} | |||
BigInt b = Factorial(25); | |||
string s = "factorial "; | |||
cout<<s<<b; // function call | |||
The function overloads the ostream operator << to return the integer value converted to string. | |||
More information about overloading of I/O Operators can be obtained from [1] and [2]. | |||
=='''Other Overloadable Operators'''== | |||
==='''Overloading of Bracket Operator'''=== | |||
The bracket operator returns a reference to the data stored in the class. | |||
Example : | |||
for(int i =0;i< myVector.size();i++) | |||
myVector[i]=120; | |||
This is equivalent to myVector.operator[](i) = 120; | |||
The overloading function is defined as - | |||
char& operator [] (int postion) { } | |||
More information on Overloading of Bracket Operator is obtained usin [2]. | |||
==='''Overloading ''new'' and ''delete'' Operators'''=== | |||
This facilitates changing memory allocation at run time i.e how much memory is allocated at run time can be changed. The syntax still remains to be new MyClass and it cannot be overloaded. | |||
More information about other overloadable operators can be obtained from [2]. | |||
=='''Advantages'''== [3] | |||
* Enables custom classes to act like primitive types - If we have a class ''vector'' which resembles standard array notation, it will be possible to array to access the individual elements. | |||
* Enables our code to interact correctly with library and template code - Overloading << to be compatible standard I/Sstream library. | |||
* Syntax becomes more intuitive. | |||
* Elegently performs complex operations behind the scenes. | |||
=='''Disadvantages'''== [3] | |||
* All operator overloaded functions must contain one user-defined type so that the basic meaning of operators is not redefined. | |||
* Some operators cannot be overloaded. | |||
* Cannot define additional operators. | |||
* Cannot change predence or associativity of operators. | |||
* Code after operating overloading maybe visiually correct but might contain serious code errors. | |||
* Operators defined by programmers may not be semantically meaningful. | |||
* Wrong return type may be provided. | |||
=Conclusion= | =Conclusion= | ||
=References= | ='''References'''= | ||
* E. Balaguruswamy [http://www.scribd.com/doc/29089248/Object-Oriented-Programming-with-C-%E2%80%9D-By-E-Balagurusamy, '''Object Oriented Programming in C++'''],Fourth edition, TataMcGraw Hill | |||
='''External Links'''= | |||
[http://cs.duke.edu/csed/tapestry/howtoe.pdf/] Overloading Arithmetic and Relational operators | |||
[http://cs.duke.edu/csed/tapestry/howtoe.pdf] Overloading Relational and I/O Operators | |||
[http://171.64.64.250/class/cs193d/handouts/25OperatorOverloading.pdf/] Overloading Relational Operators, Advantages and Disadvantages. |
Revision as of 02:10, 3 November 2010
Overloading
Method Overloading
Operator Overloading
The ability to define how user defined classes interact with operators applicable to primitive types is called Operator Overloading. In simple words, it means that a single operator can handle multiple argument types. This will help us to prevent using functional-style syntax for manipulation.
To define an overloaded operator, a function operator # is defined. The # represents the operator that is to be overloaded.
Example: operator +, operator >>
The overloading is actually done in C++ by replacing instance of every operator with the a call to the operator function.
Example: int a,b,c;
a = b*c;
It is equivalent to -
int a,b,c; a.operator = (operator+(b,c));
Some operators cannot be overloaded because of their requirement at compile-time.
Examples of such operators are:
- :: => Scope Resolution
- . => Member Selection
- ?: => Ternary Conditional
- sizeof => Size of Object
All the other operators can be overloaded.
In a broad sense, operators are classified into -
- Arithmetic Operators
- Relational Operators
- I/O Operators
The operator overloading for each type follows.
Arithmetic Operators
It includes +=,-=,*=,/=,%= and their corresponding binaries are +,-,*,/,% respectively. It is easy to implement arithmetic assignment operators as member functions and using these to implement the binary operators. Usually binary operators are implemented as independent, non-member functions. The problem in making it a member function is that it requires an object to which it can be applied [1].
Overloading of Arithmetic Assignment Operator
Example: [1]
const BigInt& BigInt::operator += (const BigInt & rhs) // post condition : rhs has to be added to *this // *this has to be returned
BigInt a = Factorial(25); BigInt b = Factorial(30);
Then the overloaded function is called as -
a+=b; BigInt c = (b+=b);
The arithmetic assignment operators should return a value. The return type should be a reference to avoid copy and it must be a constant.
More information on overloading Arithmetic Assignment operators can be obtained from [1].
Overloading of Binary Operator
Example: [2]
Let us define a class Matrix.
class Matrix
{ public : /* other member functions */ MATRIX &operator *= (double scalar);
private : static const int MATRIX_SIZE =3; double entries[MATRIX-SIZE][MATRIX_SIZE]; };
const Matrix operator *(double scalar) const
{ MyMatrix result = *this; result*=scalar; return result; }
The *= operator will scale all the elements in the matrix by a double factor. The function can now be called as
myMatrix = myMatrix * 2.3471;
More information on overloading of binary operators can be obtained from [2].
Relational Operators
Some of the relation operators are <,>,==,!,!=,&& which have a return type of bool. The relational operator overloading functions are generally globally defined so that they can be used without any worry about the order the arguments passed.
Overloading of Relational Operators
Example : [2]
bool operator==(const Date & lhs, const Date & rhs); bool operator<(const Date &lhs, const Date & rhs);
bool operator==(const Date & lhs, const Date & rhs)
{ return lhs.equal(rhs); }
bool operator<(const Date & lhs, const Date & rhs)
{ return lhs.less(rhs); }
This shows the declaration and defintion for overloading == and < operator. The function for operator == will return true if lhs is equal to rhs and false otherwise. Similarly, the function for operator < will return true if lhs is less than rhs and false otherwise.
More information on overloading of Relational Operators can be obtained from [1] and [3].
I/O Operators
Some examples of I/O Operators are << and >> i.e the ostream and istream operators. Both the operators are left-associated, meaning they evaluate the expression from left to right like,
(((cout<<1)<<2)<<endl); [2]
Overloading of I/O Operators
Example : [2]
ostream&operator<<(ostream & out, const BigInt & big)
{ out<<big.tostring(); return out; }
BigInt b = Factorial(25); string s = "factorial ";
cout<<s<<b; // function call
The function overloads the ostream operator << to return the integer value converted to string.
More information about overloading of I/O Operators can be obtained from [1] and [2].
Other Overloadable Operators
Overloading of Bracket Operator
The bracket operator returns a reference to the data stored in the class.
Example :
for(int i =0;i< myVector.size();i++) myVector[i]=120;
This is equivalent to myVector.operator[](i) = 120;
The overloading function is defined as -
char& operator [] (int postion) { }
More information on Overloading of Bracket Operator is obtained usin [2].
Overloading new and delete Operators
This facilitates changing memory allocation at run time i.e how much memory is allocated at run time can be changed. The syntax still remains to be new MyClass and it cannot be overloaded.
More information about other overloadable operators can be obtained from [2].
==Advantages== [3]
- Enables custom classes to act like primitive types - If we have a class vector which resembles standard array notation, it will be possible to array to access the individual elements.
- Enables our code to interact correctly with library and template code - Overloading << to be compatible standard I/Sstream library.
- Syntax becomes more intuitive.
- Elegently performs complex operations behind the scenes.
==Disadvantages== [3]
- All operator overloaded functions must contain one user-defined type so that the basic meaning of operators is not redefined.
- Some operators cannot be overloaded.
- Cannot define additional operators.
- Cannot change predence or associativity of operators.
- Code after operating overloading maybe visiually correct but might contain serious code errors.
- Operators defined by programmers may not be semantically meaningful.
- Wrong return type may be provided.
Conclusion
References
- E. Balaguruswamy Object Oriented Programming in C++,Fourth edition, TataMcGraw Hill
External Links
[1] Overloading Arithmetic and Relational operators
[2] Overloading Relational and I/O Operators
[3] Overloading Relational Operators, Advantages and Disadvantages.