Total members 11895 |It is currently Sat Dec 21, 2024 4:05 pm Login / Join Codemiles

Java

C/C++

PHP

C#

HTML

CSS

ASP

Javascript

JQuery

AJAX

XSD

Python

Matlab

R Scripts

Weka





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;
}




_________________
Please recommend my post if you found it helpful


Author:
Beginner
User avatar Posts: 109
Have thanks: 5 time

updated.

_________________
M. S. Rakha, Ph.D.
Queen's University
Canada


Author:
Mastermind
User avatar Posts: 2715
Have thanks: 74 time
Post new topic Reply to topic  [ 2 posts ] 

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



Topic Tags

C++ OOP






Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
All copyrights reserved to codemiles.com 2007-2011
mileX v1.0 designed by codemiles team
Codemiles.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com