This preview has intentionally blurred sections. Sign up to view the full version.View Full Document
Unformatted text preview: [ Viewing Hints ] [ Exercise Solutions ] [ Volume 2 ] [ Free Newsletter ] [ Seminars ] [ Seminars on CD ROM ] [ Consulting ] Thinking in C++, 2nd ed. Volume 1 ©2000 by Bruce Eckel [ Previous Chapter ] [ Table of Contents ] [ Index ] [ Next Chapter ] 7: Function Overloading & Default Arguments One of the important features in any programming language is the convenient use of names. When you create an object (a variable), you give a name to a region of storage. A function is a name for an action. By making up names to describe the system at hand, you create a program that is easier for people to understand and change. It’s a lot like writing prose – the goal is to communicate with your readers. A problem arises when mapping the concept of nuance in human language onto a programming language. Often, the same word expresses a number of different meanings, depending on context. That is, a single word has multiple meanings – it’s overloaded . This is very useful, especially when it comes to trivial differences. You say “wash the shirt, wash the car.” It would be silly to be forced to say, “shirt_wash the shirt, car_wash the car” just so the listener doesn’t have to make any distinction about the action performed. Human languages have built-in redundancy, so even if you miss a few words, you can still determine the meaning. We don’t need unique identifiers – we can deduce meaning from context. Most programming languages, however, require that you have a unique identifier for each function. If you have three different types of data that you want to print: int , char , and float , you generally have to create three different function names, for example, print_int( ) , print_char( ) , and print_float( ) . This loads extra work on you as you write the program, and on readers as they try to understand it. In C++, another factor forces the overloading of function names: the constructor. Because the constructor’s name is predetermined by the name of the class, it would seem that there can be only one constructor. But what if you want to create an object in more than one way? For example, suppose you build a class that can initialize itself in a standard way and also by reading information from a file. You need two constructors, one that takes no arguments (the default constructor) and one that takes a string as an argument, which is the name of the file to initialize the object. Both are constructors, so they must have the same name: the name of the class. Thus, function overloading is constructors, so they must have the same name: the name of the class....
View Full Document
- Spring '11
- default arguments