## 6. Overloading and Operators

### 6. Overloading and Operators

We wish to add doubles to complex numbers and complex numbers to doubles:

Complex z1(-23.0, 5.3);

Complex z2(2.0, 3.0);

Complex z3 = z1 * z2;

Complex z4 = 2.0 * z4;

Explain how this code solves the problem:

friend Complex operator * (const Complex& c, double d);

friend Complex operator * (double d, const Complex& c);

Explain

Cuchulainn

Posts: 669
Joined: Mon Dec 18, 2006 2:48 pm
Location: Amsterdam, the Netherlands

Can the following 'operators' be overloaded and where would they be used;

*

()

[]

%

&

.

->

^

Cuchulainn

Posts: 669
Joined: Mon Dec 18, 2006 2:48 pm
Location: Amsterdam, the Netherlands

You can overload all of the operators you mentioned except .

You can also overload them in a number of ways. You can define exponentiation via ^ however this would be a bit strange to another programmer. Similarly you can overload (). For example you could make a call option object with private data member Strike and use the () operator to return the price like this

CallOption::operator () (double Spot) const

{

return (Spot > Strike) ? Spot- Strike : 0 ;

}
ImplicitScheme

Posts: 6
Joined: Thu Nov 04, 2010 7:01 pm

Yes, '.' cannot be overloaded.

Regarding () this is used as function objects in STL.

BTW did you know , can be overloaded? Here is some cool code in Boost:

vector<int> myVec;

myVec += 10,11,45,80,23,99;

BOOST_ASSERT(myVec.size() == 6);

Cuchulainn

Posts: 669
Joined: Mon Dec 18, 2006 2:48 pm
Location: Amsterdam, the Netherlands

I was aware that it could be overloaded only because I happen to know which operators can't be.

Your code is equal parts of interesting and cool. Is there more information about Boost on your website anywhere ?
ImplicitScheme

Posts: 6
Joined: Thu Nov 04, 2010 7:01 pm

The boost examples are here

http://www.datasimfinancial.com/forum/v ... .php?t=111

This may also be of interest

www.datasim-press.com

Cuchulainn

Posts: 669
Joined: Mon Dec 18, 2006 2:48 pm
Location: Amsterdam, the Netherlands

### Re: 6. Overloading and Operators

How would you implement a sparsed matrix using just the standard STL containers?
sabahat

Posts: 1
Joined: Tue Nov 11, 2014 8:59 am

Return to C++ Certification and Examinations: Intermediate Level

### Who is online

Users browsing this forum: No registered users and 1 guest