Sams Teach Yourself C in 21 Days

(singke) #1
The C++ Programming Language 655

BD2


Doing Operations in C++ ..................................................................................


The operators available in C++ are virtually the same as those available in C++. This
means that everything you have already learned regarding operators applies.
C++ adds one additional operator that is used for error handling. This operator is the
throwoperator. It is beyond the scope of this book to go into details on how the throw
operator and exception handling work within C++. Understand that the throwoperator
enables you to better handle errors in C++.

Working with Functions in C++ ........................................................................


Yesterday, you were shown an example of overloading functions in C++. You saw that a
function’s name can be used more than once. In the following sections, you will learn the
specifics of overloading functions within C++. You will also learn about a few other fea-
tures of C++ that relate to functions, including


  • Using default values for function parameters

  • Using inline functions


Overloading Functions ..................................................................................


Overloading functions is the simplest form of polymorphism supported by C++. As you
saw yesterday, C++ does not complain if you use the same function name more than
once. The capability to reuse a function name enables you to create programs that are
adaptive and, thus, smarter. By creating a function that can be called in multiple ways,
you are providing the user of the function with options. Consider the examples used yes-
terday. In the square listing, you learned that a person can draw a square in multiple
ways. Whether the square function was called with two points or with a point and the
width, the square was drawn.
In order for a C++ compiler to support the polymorphic nature of overloading functions,
there are a few rules you must follow. You allow a function to accept different parameters
by declaring and defining multiple instances of the function. Each unique instance must
have at least one parameter that is different from the other instances. This difference
must be in the data type. Consider the following two function calls for a function called
rectangle:
int rectangle( int topleftx, int toplefty, int width, int length );
int rectangle( int topleftx, int toplefty, int bottomrightx, int
bottomright y );

37 448201x-Bonus2 8/13/02 11:18 AM Page 655

Free download pdf