Switch to full style
For C/C++ coders discussions and solutions
Post a reply

What is Operator Overloading? !!!

Wed Jul 04, 2007 12:36 am

What is Operator Overloading? How to use operator overloading in C++
-----------------------------------------------


C++ lets you build operators that implement unary and binary operations on objects o classes. This is called as Operator overloading. You can write a function to make the operator do your custom operation. For example:

cpp code
Date dt1( 1,2, 2004);
Date dt2( 2,4, 2005);
Dt1+=100;
Int diff = dt2-dt1;


Here, the plus operator and the subtract operator have been overloaded to perform custom operations for the Date class.

Another example in class definition:
cpp code
class NewNumberType
{
double real,
imag;
public:
NewNumberType( double real = 0., double imag = 0.);
NewNumberType operator+(const NewNumberType&) const;
};


NewNumberType::NewNumberType( double r, double i )
{
real = r; imag = i;
}

// Overloading + (plus) operator
NewNumberType NewNumberType::operator+ (const NewNumberType& c) const
{
NewNumberType result;
result.real = (this->real + c.real);
result.imag = (this->imag + c.imag);
return result;
}

int main()
{
NewNumberType x(4,4);
NewNumberType y(6,6);
NewNumberType z = x + y;
}




Re: What is Operator Overloading? !!!

Wed Jan 23, 2013 11:42 pm

updated.

Post a reply
  Related Posts  to : What is Operator Overloading? !!!
 operator overloading     -  
 unary operator overloading     -  
 Operator overloading easy code     -  
 overloading << and >>     -  
 Function Overloading     -  
 operator int()     -  
 Using the ? Operator     -  
 What is the % operator     -  
 Object without new Operator     -  
 trinary operator     -  

Topic Tags

C++ OOP