Operator overloading provides a way to define and use operators such as +, -, *, /, and [] for user defined types such as classes and enumerations.
Operator Overloading Rules :
Only existing operator symbols may be overloaded. New symbols cannot be defined.
The operators ::, .*, . and ?: cannot be overloaded.
Operators =, [], () and -> can only be defined as members of a class and not as global functions.
At least one operand for any overload must be a class or enumeration type. One cannot overload operators involving only built-in data types such as "int".
The number of operands for an operator cannot be changed. For example, addition, +, may not be defined to take other than two arguments regardless of data type.
Operator Overloading does not change operator precedence.
class Number
{
public:
Number(int num = 0)
{
this->number = num;
}
Number operator+(const Number &other)
{
Number temp;
temp.number = this->number + other.number;
return temp;
}
// in the below case if you do just a++ then the return is simply ignored, but incase of c = a++ the return assigned "a"
// For the prefix method, the calling object exists before, during and after the method execution, so a reference can be used to avoid extra copies.
Number& operator++() // simple or regular prefix increment
{
number += number;
return *this;
}
//For postfix method, the 'temp' object goes out of scope when the ++ method returns. Returning a reference to an out of scope object will coredump.
Number operator++(int)// postfix, we create a dummy overloaded function(for uniqueness) and return by value so that a copy is made and returned
{
Number temp(number);
this->number += number;
return temp;
}
// we declare this here but the actual method definition can be written anywhere as long as the NUMBER class is declared.
friend Number operator+(const int i, const Fraction f);
void print() { cout << number<< endl; }
private:
int number =0 ;
};
int main() {
Number a(2),b(4),c;
c = a + b;
c.print(); // output will be 2 + 4 = 6
c = ++a; //prefix
c.print(); // output will be 12
c = a++;// postfix
c.print(); // output will still be 12
a.print(); // output will be 24
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment