X hits on this document

36 views

0 shares

0 downloads

0 comments

1 / 14

Much of the material in these notes is derived from the Hubbard book (see course outline).

OOP II

Overloading Operators, the this Pointer, friend Functions

The C++ operators are defined to work on the fundamental types (e.g. + works on int, float, etc.).  When you create a class you sometimes need to define operations for the class, and sometimes you would like to use the “standard” operators rather than, say, define an add(x, c) function.  These operators may work slightly differently on the structured objects of the class than they do on data objects of the fundamental types.  The nice thing about C++ (as opposed to, say, Pascal, COBOL, etc.) is that we can redefine the = or + operator to work on the new type that we create by defining a class.

Assignment Operator

The assignment operator is used to copy the value of one object to another.  Just like the default constructor and copy constructor it is automatically overloaded for our new class even if we do not explicitly define it; However, just like the constructors we can explicitly define it if we wish.  Ex.

class Rational{

public:

Rational (int=0, int=1);

Rational (const Rational&);

Rational& operator=(const Rational&);

private:

int num;

int den;

};

The function name for the assignment operator is “operator=”.  So operator overloading is actually no different from function overloading.  

The prototype:

Rational& operator= (const Rational&);

Return    fn nametype of input

typeparameter

and in general, where T is a placeholder that stands for “any type,” the syntax is:

T& operator= (const T&);

overloading.doc1 of 14

Document info
Document views36
Page views36
Page last viewedFri Oct 28 12:59:16 UTC 2016
Pages14
Paragraphs547
Words2961

Comments