Question

What is the best way to over load a operator, and what is the point. I...

What is the best way to over load a operator, and what is the point. I don't quiet understand what it is doing.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Answer:

To overload an operator, a special operator function is defined inside the class as:

class className
{
... .. ...
public
returnType operator symbol (arguments)
{
... .. ...
}
... .. ...
};
Here, returnType is the return type of the function.
The returnType of the function is followed by operator keyword.
Symbol is the operator symbol you want to overload. Like: +, <, -, ++
You can pass arguments to the operator function in similar way as functions.


Example: Operator overloading in C++ Programming
#include <iostream>
using namespace std;
class Test
{
private:
int count;
public:
Test(): count(5){}
void operator ++()
{
count = count+1;
}
void Display() { cout<<"Count: "<<count; }
};
int main()
{
Test t;
// this calls "function void operator ++()" function
++t;
t.Display();
return 0;
}

Output

Count: 6
This function is called when ++ operator operates on the object of Test class (object t in this case).

In the program,void operator ++ () operator function is defined (inside Test class).

This function increments the value of count by 1 for t object.

Things to remember
Operator overloading allows you to redefine the way operator works for user-defined types only (objects, structures). It cannot be used for built-in types (int, float, char etc.).
Two operators = and & are already overloaded by default in C++. For example: To copy objects of same class, you can directly use = operator. You do not need to create an operator function.
Operator overloading cannot change the precedence and associatively of operators. However, if you want to change the order of evaluation, parenthesis should be used.
There are 4 operators that cannot be overloaded in C++. They are :: (scope resolution), . (member selection), .* (member selection through pointer to function) and ?: (ternary operator).

Add a comment
Know the answer?
Add Answer to:
What is the best way to over load a operator, and what is the point. I...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
Active Questions
ADVERTISEMENT