More Operator Overloading


Automatic type conversion and explicit

Implicit type conversion

 

 

Type conversion and classes

General guideline: 1-argument constructors should be explicit unless there is a good reason to allow implicit type conversions.

Example: Suppose we remove explicit from the 1-argument constructor in the Polynomial class. Consider the following code:

Polynomial p1;

Polynomial p2 = 4.1;

p1 = 3.2;

p2 += 8.7;

Polynomial p3;

p3 = p2 + 4.2;
 
p1 = 6.5 + p3;

Member vs Non-Member Revisited

Overloading operatorX

Suppose + was a member function of the Polynomial class. Consider the following (where p is a Polynomial):

p + 3.2

 

 

3.2 + p

 

 

Problem with non-member functions:

Solution 1:

 

 

Solution 2:

 

 


friend keyword

A friend can

A class can be friends with

How friendship is declared:

 

 

Friendship is not:

Use with caution! Use a member function when you can and a friend function when you have to.


Overloading relational operators

Convention:

 

Make sure to be consistent: