The following are the most OOP (Object Oriented Programmin) features:
- Abstraction
- Encapsulation and data hiding
- Inheritance
- Reusability of code
I will now summarize what I read about classes and I should remember.
The class is the single most important C++ enhancement for implementing these features and tying them together!
Procedural and Object-Oriented Programming
In short, with a procedural approach, you first concentrate on the procedures you will follow and then think about how to represent the data.
In short, with an OOP approach, you concentrate on the object as the user perceives it, thinking about the data you need to describe the object and the operations that will describe the user's interaction with the data. After you develop a description of that interface, you move on to decide how to implement the interface and data storage. Finally, you put together a program to use your new design.
Abstraction and Classes
In computing, abstraction is the crucial step of representing information in terms of its interface with the user. That is, you abstract the essential operational features of a problem and express a solution in those terms.
In the softball example (sorry, not showen here), the interface describes how the user initializez, updates and display the data. From abstraction, it is a short step to the user-defined type, which in C++ is a class design that implements the abstract interface.
What is a type?
At first you tend to think of a datatype in terms of its appearance--how it is stored in memory.
A char, for example is 1 byte of memory, and a double is often 8 bytes of memory.
But a little reflection leads you to conclude that a data type is also defined in terms of operations that can be performed on it.
For example, the int type can use all the arithmetic operations. You can add, subtract, multiply, and divide integers. You can also use the modulus operator (%) with them.
On the other hand, consider pointers. A pointer might very well require the same amount of memory as an int. It might even be represented internally as an integer. But a pointer doesn't
allow the same operations that an integer does. You can't for example, multiply two pointers by eachother.
Thus when you declare a variable as an int or as a pointer-to-float, you're not just allocating memory--you are also establishing which operations can be performed with the variable.
In short, specifying a basic type does three things:
- It determines hwo much memory is needed for a data object.
- It determines how the bits in memory are interpreted. (A long and a float might use the same number of bits in memory, but they are translated into numeric values differently.)
- It determines what operations, or methods, can be performed using the data object.
For built-in types, the information about operations is built in to the compiler. But when you define a user-defined type in C++, you have to provide the same kind of information yourself.
In exchange for this extra work, you gain the power and flexibility to custom fit new data types to match real-world requirements.
Classes in C++
A class is a C++ vehicle for stranslating an abstraction to a user-defined-type. It combines data representation and methods for manipulating that data into one neat package.
To define a class, Generally, a class specification has two parts:
- A class declaration, which describes the data component, in terms of data members, and the public interface, in terms of member functions, termed methods
- The class method definitions, which describe how certain class member functions are implemented
Roughly speaking, the class declaration provides a class overview, whereas the method definitions supply the details.
What is an Interface?
For classes, we speak of the public interface. In this case, the public is the program using the class, the interacting system consists of the class objects, and the interface consists of the methods provided by whoever wrote the class. The interface enables you, the programmer, to write code that interacts with class objects, and thus it enables the program to use the class objects. For example, to find the number of characters in a string object, you don't open up the object to what is inside; you just use the size() method provided by the class creators. It turns out that the class design denies direct access to the public user. But the public is allowed to use the size() method. The size() method, then, is part of the public interface between the user and a string class object.
Similarly, the getline() method is part of the istream class public interface.
If you want a more personal relationship, instead of thinking of the program using a class as the public user, you can think of the person writing the program using the class as the public user. But in any case, to use a class, you need to know its public interface; to write a class, you need to create its public interface.
The keywords private public describe access control for class members.
Any program that uses an object of a particular class can access the public portions directly. A program can access the private members of an object only by using the public member functions. Thus, the public member functions act as go-betweens between a program and an object's private members; they provide the interface between object and program.
data hiding, this isulation of data from direct access by a program is called data hiding.
A class design attempts to separate the public interface from the specifics of the implementation. The public interface represents the abstraction component of the design.
Gathering the implementation details together and separating them from the abstraction is called encapsulation. Data hiding (putting data into the private section of a class) is an instance of encapsulation, and so hiding functional details of an implementation in the private section.
Another example of encapsulation is the usual practice of placing class function definitions in a seperate file from the class declaration.
Note that data hiding not only prevents you form accessing data directly, but it also absolves you (in the roll as user of the class) from needing to know how the data is represented.
For example a class show() member can display the total value of a holding, this value can be stored as part of an object, or it can be calculated when needed.
From the standpoint of the user, it makes no difference which approach is used.
What you need to know is what the different member functions accomplish; that is, you need to know what kinds of arguments a member function takes and what kind of return value it has.
The principle is to separate the details of the implementation from the design of the interface.
If you later find a better way to implement the data representation or the details of the member functions, you can change those details without changing the program interface, and that makes programs much easier to maintain.
Implementing Class Member Functions
You still have to create the second part of the class specification: providing code for those member functions represented by a prototype in the class declaration. Member function definitions are much like regular functions. Each has a function header and a function body. Member function definitions can have return types and arguments. But they also have two special characteristics:
- When you define a member function, you use the scope-resolution operator (::) to identify the class to which the function belongs
- Class methods can access the private components of the class
First, the function header for a member function uses the scope-resolution operator (::) to indicate to which class the function belongs.
See this example:
void Stock::update(double price)
This notation means you are defining the update() function that is member of the Stock class.
Thus, the scope-resolution operator resolves the identity of the class to which a method definition applies. We say that the identifier update() has class scope. Other member functions of the Stock class can, if necessary, use the update() method without using the scope-resolution operator. That is because they belong to the same class, making update() in scope.
The second special characteristic of methods is that a method can access the private members of a class. For example, the show() method can use code like this:
cout << "Company: " << company
<< " Shares: " << shares << endl;
<< " Share Price: $" << share_val
<< " Total Worth: $" << total_val << endl;
Where all those variables are in the private section of the class.
Here company, shares, and so on are private data members of the Stock class. If you try to use a nonmember function to access these data members, the compiler stops you cold in your tracks. (However, friend functions, later discussed provide an exception).
Which Object Does a Method Use?
Now we come to one of the most important aspects of using objects: how you apply a class method to an object. Code such as
shares += num;
uses the shares member of an object. But which object? That is an excellent question! To answer it, first consider how you create an object. The simplest way is to declare class variables:
Stock kate, joe;
This creates two objects of the Stock class, one named kate and one named joe.
Next, consider how to use a member function with one of these objects. The answer is, as with structures and structure members, is to use the membership operator:
kate.show(); // the kate object calls the member function
joe.show(); // the joe object calls the member function
The first call here invokes show() as a member of the kate object. This means the method interprets shares as kate.shares and share_val as kate.share_val. Similarly, the call joe.show() method interprets shares and share_val as joe.shares and joe.share_val respectively.
Each new object you create contains storage for its own internal variables, the class members. But all objects of the same class share the same set of class methods, with just one copy of each method.
Suppose, for example, that kate and joe are Stock objects. In that case, kate.shares occupies one chunk of memory and joe.shares occupies a second chunk of memory. But kate.show() and joe.show() both invoke the same method--that is, both execute the same block of code. They just apply the code to different data. Calling a member function is what some OOP languages term sending a message. Thus, sending the same message to two different objects invoke the same method but applies it to two different objects.
When the Stock class works as you want it to, you can use it as a user-defined type in other programs. The critical point in using the new type is to understand what member functions do;
You shouldn't have to think about the implementation details.
The Client/Server Model
OOP programmers often discuss program design in terms of a client/server model. In this conceptualization, the client is the program that uses the class. The class declaration, including the class methods, constitude the server, which is a resource that is available to the programs that need it. The client uses the server through the publicly defined interface only. This means that the client's only responsibility, and, by extension, the client's programmer's only responsibility, is to knwo that interface. The server's responsibility, and by extension, the server's designer's responsibility, is to see that the server reliably and accurately performs according to that interface. Any changes the server designer makes to the class design should be to details of the implementation, not to the interface. This allows programmers to improve the client and the server independently of each other, without changes in the server having unforseen repercussions on the client's behavior.
Full Qualified Name
char * Bozo::Retort()
The full, or qualified name of the above funtion is: Bozo::Retord(). The name Retort(), on the other hand, is an abbreviation of the qualified name, and it can be used only in certain circumstances, such as in the code for the class methods.
To create an object, which is a particular example of a class, you use the class name as if it where a type name:
Bozo bozetta;
This works because a class is a user-defined type.
You invoke a class member function, or method, by using a class object. You do so by using the dot membership operator:
This invokes the Retort() member function, and whenever the code for that function refers to a particular data member, the function uses the value that member has in the bozetta object.
zaterdag 30 juni 2007
vrijdag 29 juni 2007
static duration variables
To create a static duration variable with external linkage, you declare it outside any block.
To create a static duration variable with internal linkage, you declare it outside any block and use the static storage class modifier.
To create a static duration variable with no linkage, you declare it inside a block, using the static modifier.
See example:
...
int global = 1000; // static duration, external linkage
static int one_file = 50; // static duration, internal linkage
int main()
{
...
}
void funct1(int n)
{
static int count = 0; // static duration, no linkage
int llama = 0;
}
To create a static duration variable with internal linkage, you declare it outside any block and use the static storage class modifier.
To create a static duration variable with no linkage, you declare it inside a block, using the static modifier.
See example:
...
int global = 1000; // static duration, external linkage
static int one_file = 50; // static duration, internal linkage
int main()
{
...
}
void funct1(int n)
{
static int count = 0; // static duration, no linkage
int llama = 0;
}
donderdag 28 juni 2007
external linkage, internal linkage
A name with external linkage can be shared accross files.
A name with internal linkage can be shared by functions within a single files.
Names of automatic variables have no linkage because they are not shared.
A name with internal linkage can be shared by functions within a single files.
Names of automatic variables have no linkage because they are not shared.
woensdag 27 juni 2007
Storage Duration, Scope, and Linkage
C++ uses three separate schemes for storing data, and the schemes differ in how long they preserve data in memory:
- Automatic storage duration--Variables declared inside a function definition--including function parameters--have automatic storage duration. They are created when program execution enters the function or block in which they are defined, and the memory used for them is freed when execution leaves the function or block. C++ has two kinds of automatic storage duration variables.
- Static storage duration--Variables defined outside a function definition or else by using the keyword static have static storage duration. They persist for the entire time a program is running. C++ has three kinds of static storage duration variables.
- Dynamic storage duration--Memory allocated by the new operator persists until it is freed with the delete operator or until the program ends, whichever comes first. This memory has dynamic storage duration and somethimes is termed the free store.
Scope and Linkage
Scope describes how widely visible a name is in a file (translation unit). For example, a variable defined in a function can be used in that function, but not in another, whereas a variable defined in a file above the function definitions can be used in all the functions. Linkage describes how a name can be shared in different units. A name with external linkage can be shared accross files, and a name with internal linkage can be shared by functions within a single file.
Names of automatic variables have no linkage because they are not shared.
A C++ variable can have one of several scopes. A variable that has local scope (also termed block scope) is known only within the block in which it is defined. Recall that a block is a series of statements enclosed in braces. A function body, for example, is a block, but you can have other blocks nested within the function body. A variable that has global scope (also termed file scope) is known throughout the file after the point where it is defined. Automatic variables have a local scope, and a static variable can have either scope, depending on how it is defined.
Names used in a function prototype scope are known just within the parentheses enclosing the argument list. Members declared in a class have class scope (see later blogs), Variables declared in a namespace have namespace scope. (Now that namespaces have been added to the C++ language, the global scope has become a special case of namespace scope.)
C++ functions can have class scope or namespace scope, including global scope, but they can't have local scope. (Because a function can't be defined inside a block, if a function were to have local scope, it could only be known to itself, and hence couldn't be called by another function. Such a function couldn't function.) I guess you also should know a function can not be defined in a function, a function cannot be nested in a function.
The various C++ storage choiches are characterized by their storage duration, their scope, and their linkage.
If you like to read more about this, buy a book on it like: C++ primer plus by Stephen Prata, that is where most of my blogs are based on.
- Automatic storage duration--Variables declared inside a function definition--including function parameters--have automatic storage duration. They are created when program execution enters the function or block in which they are defined, and the memory used for them is freed when execution leaves the function or block. C++ has two kinds of automatic storage duration variables.
- Static storage duration--Variables defined outside a function definition or else by using the keyword static have static storage duration. They persist for the entire time a program is running. C++ has three kinds of static storage duration variables.
- Dynamic storage duration--Memory allocated by the new operator persists until it is freed with the delete operator or until the program ends, whichever comes first. This memory has dynamic storage duration and somethimes is termed the free store.
Scope and Linkage
Scope describes how widely visible a name is in a file (translation unit). For example, a variable defined in a function can be used in that function, but not in another, whereas a variable defined in a file above the function definitions can be used in all the functions. Linkage describes how a name can be shared in different units. A name with external linkage can be shared accross files, and a name with internal linkage can be shared by functions within a single file.
Names of automatic variables have no linkage because they are not shared.
A C++ variable can have one of several scopes. A variable that has local scope (also termed block scope) is known only within the block in which it is defined. Recall that a block is a series of statements enclosed in braces. A function body, for example, is a block, but you can have other blocks nested within the function body. A variable that has global scope (also termed file scope) is known throughout the file after the point where it is defined. Automatic variables have a local scope, and a static variable can have either scope, depending on how it is defined.
Names used in a function prototype scope are known just within the parentheses enclosing the argument list. Members declared in a class have class scope (see later blogs), Variables declared in a namespace have namespace scope. (Now that namespaces have been added to the C++ language, the global scope has become a special case of namespace scope.)
C++ functions can have class scope or namespace scope, including global scope, but they can't have local scope. (Because a function can't be defined inside a block, if a function were to have local scope, it could only be known to itself, and hence couldn't be called by another function. Such a function couldn't function.) I guess you also should know a function can not be defined in a function, a function cannot be nested in a function.
The various C++ storage choiches are characterized by their storage duration, their scope, and their linkage.
If you like to read more about this, buy a book on it like: C++ primer plus by Stephen Prata, that is where most of my blogs are based on.
Seperate Compilation
To seperate compile files, you have to split your source file into several files.
This is an example what to put in a header file:
- Function prototypes
- Symbolic constants defined using #define or const
- Structure declarations
- Class declarations
- Template declarations
- Inline functions
Data declared const and inline functions have special linkage properties (described shortly) that allow them to be placed in header files without causing problems.
For include files, when you created them yourself, in the source where you use them, use "includefile.h" instead of because if the include file is in angle brackets, because the C++ compiler then looks in the hosts system files directory, that holds the standard header files. But if the header file is enclosed in double quotations marks, the compiler first looks in the current working directory or the sourcecode directory.
So you should use double quotations marks if you want to use your own header files/ include files.
You should include a header file just once in a file. That might seem to be an easy thing to remember, but it's possible yo include a header file several times without knowing you did so.
For example you might use a header file that includes another header file. There's a standard C/C++ technique for avoiding multiple inclusions of header files. It's based on the preprocessor #ifndef (for if not defined) directive. A code segment like
#ifndef COORDIN_H_
...
#endif
Means process the statements between the #ifndef and #endif only if the name COORDIN_H_ has not been defined previously by the preprocessor #define directive.
By the way, although we've discussed separate compilation in terms of files, the C++ Standard use the term translation unit instead of file in order to preserve greater generality; the file metaphore is not the only possible way to organize information for a computer.
Multiple Library linking
The C++ Standard allows each compiler designer the latitude to implement name decoration or mangling as it sees fit. So you should be aware that binary modules (object-code files) created with different compilers will, most likely, not linked properly. That is, the two compilers will generate different decorated names for the same function. This name difference will prevent the linker from matching the function call generated by one compiler with the function definition generated by a second compiler. When attempting to link compiled modules, you should make sure that each object file or library was generated with the same compiler. If you are provided with the source code, you can usually resolve link errors by recompiling the source with your compiler.
This is an example what to put in a header file:
- Function prototypes
- Symbolic constants defined using #define or const
- Structure declarations
- Class declarations
- Template declarations
- Inline functions
Data declared const and inline functions have special linkage properties (described shortly) that allow them to be placed in header files without causing problems.
For include files, when you created them yourself, in the source where you use them, use "includefile.h" instead of
So you should use double quotations marks if you want to use your own header files/ include files.
You should include a header file just once in a file. That might seem to be an easy thing to remember, but it's possible yo include a header file several times without knowing you did so.
For example you might use a header file that includes another header file. There's a standard C/C++ technique for avoiding multiple inclusions of header files. It's based on the preprocessor #ifndef (for if not defined) directive. A code segment like
#ifndef COORDIN_H_
...
#endif
Means process the statements between the #ifndef and #endif only if the name COORDIN_H_ has not been defined previously by the preprocessor #define directive.
By the way, although we've discussed separate compilation in terms of files, the C++ Standard use the term translation unit instead of file in order to preserve greater generality; the file metaphore is not the only possible way to organize information for a computer.
Multiple Library linking
The C++ Standard allows each compiler designer the latitude to implement name decoration or mangling as it sees fit. So you should be aware that binary modules (object-code files) created with different compilers will, most likely, not linked properly. That is, the two compilers will generate different decorated names for the same function. This name difference will prevent the linker from matching the function call generated by one compiler with the function definition generated by a second compiler. When attempting to link compiled modules, you should make sure that each object file or library was generated with the same compiler. If you are provided with the source code, you can usually resolve link errors by recompiling the source with your compiler.
dinsdag 26 juni 2007
Explicit Specializations (Templates)
Suppose you define a structure like the following:
struct job
{
char name[40];
double salary;
int floor;
};
Also, suppose you want to be able to swap the contents of the two structures. The original template, the one before this blog, uses the following code to effect a swap:
temp = a;
a = b;
b = temp;
Because C++ allows you to assign one structure to another, this works fine, even if type Any is a
job structure. But suppose you want only to swap the salary and floor members, keeping the name members unchanged. This requires different code, but the arguments to Swap() would be the same as for the first case (references to two job structures), so you can't use template overloading to supply alternative code.
However, you can supply a specialized function definition, called an explicit specialization, with the required code, If the compiler finds a specialized definition that exactly matches a function call, it uses that definition without looking for templates.
The specialization mechanism has changed with the evolution of C++. We'll look at the current form as mandated by the C++ Standard.
- For a given function name, you can have a non-template function, a template function, and an explicit specialization template function, along with overloaded versions of all of these.
- The prototype and definition for an explicit specialization should be preceded by template <> and should mention the specialized type by name.
- A specialization overrides the regular template, and a non-template function overides both.
Here's how prototypes for swapping type job structures would look for these three forms:
// non-template function prototype
void Swap(job &, job &);
// template prototype
template
void Swap(Any &, Any &);
// explicit specialization for the job type
template <> void Swap(job &, job &);
As mentioned previously, if more than one of these prototypes is present, the compiler chooses the non-template version over explicit specializations and template versions, and it chooses an explicit specialization over a version generated from a template. For example, in the following code, the first call to Swap() uses the general template, and the second call uses the explicit specialization, based on the job type:
...
template // template
void Swap(Any &, Any &);
// explicit specialization for the job type
template <> void Swap(job &, job &);
int main()
{
double u, v;
...
Swap(u, v); // use template
job a, b;
...
Swap(a, b); // use void Swap(job &, job &)
}
The in Swap is optional because the function argument types indicate that this is a specialization for job. Thus the prototype can also be written this way:
template <> void Swap(job &, job &); // simpler form
struct job
{
char name[40];
double salary;
int floor;
};
Also, suppose you want to be able to swap the contents of the two structures. The original template, the one before this blog, uses the following code to effect a swap:
temp = a;
a = b;
b = temp;
Because C++ allows you to assign one structure to another, this works fine, even if type Any is a
job structure. But suppose you want only to swap the salary and floor members, keeping the name members unchanged. This requires different code, but the arguments to Swap() would be the same as for the first case (references to two job structures), so you can't use template overloading to supply alternative code.
However, you can supply a specialized function definition, called an explicit specialization, with the required code, If the compiler finds a specialized definition that exactly matches a function call, it uses that definition without looking for templates.
The specialization mechanism has changed with the evolution of C++. We'll look at the current form as mandated by the C++ Standard.
- For a given function name, you can have a non-template function, a template function, and an explicit specialization template function, along with overloaded versions of all of these.
- The prototype and definition for an explicit specialization should be preceded by template <> and should mention the specialized type by name.
- A specialization overrides the regular template, and a non-template function overides both.
Here's how prototypes for swapping type job structures would look for these three forms:
// non-template function prototype
void Swap(job &, job &);
// template prototype
template
void Swap(Any &, Any &);
// explicit specialization for the job type
template <> void Swap
As mentioned previously, if more than one of these prototypes is present, the compiler chooses the non-template version over explicit specializations and template versions, and it chooses an explicit specialization over a version generated from a template. For example, in the following code, the first call to Swap() uses the general template, and the second call uses the explicit specialization, based on the job type:
...
template
void Swap(Any &, Any &);
// explicit specialization for the job type
template <> void Swap
int main()
{
double u, v;
...
Swap(u, v); // use template
job a, b;
...
Swap(a, b); // use void Swap
}
The
template <> void Swap(job &, job &); // simpler form
Function Templates
A function template is a generic function description; that is, it defines a function in terms of a generic type for which a specific type, such as int or double, can be substituted.
By passing a type as parameter to a template, you cause the compiler to generate a function for that particular type. Because templates let you program in terms of a generic type instead of a specific type, the process is somethimes called generic programming.
Because types are represented by parameters, the template feature is somethimes referred as parameterized types.
Function templates enable you to define a function in terms of some arbitrary type. For example, you can set up a swapping template like this:
template
void Swap(Any &a, Any &b)
{
Any temp;
temp = a;
a = b;
b = temp;
}
The first line specifies that you are setting up a template and you're naming the arbitrary type Any. The keyword template and class are obligatory, except you can use the keyword typename instread of class. Also, you must use the angle brackets. The type name (Any, in this example) is your choice, as long as you follow the usual C++ naming rules; many programmers use simple names such as T. The rest of the code describes the algorithm for swapping two values of type Any. The template does not create any functions. Instead, it provides the compiler with directions about how to define a function. If you want a function to swap ints, then the compiler creates a function following the template pattern, substituting int for Any. Similarly, if you need a function to swap doubles, the compiler follows the template, substituting the double type for Any.
The keyword typename is a recent addition to C++. You can use it instead of the keyword class in this particular context. That is, you can write the template definition this way:
template
void Swap(Any &a, Any &b)
{
Any temp;
temp = a;
a = b;
b = temp;
}
The typename keyword makes it a bit more obvious that the parameter Any represents a type;
however, large libraries of code have already been developed by using the older keyword class. The C++ standard treats the two keywords identically when they are used in this context.
To let the compiler know that you need a particular form of swap function, you just use a function called Swap() in your program. The compiler checks the argument types you use and then generates the corresponding function.
In a program, the template could be used as follows:
template // or typename Any
void Swap(Any &a, Any &b);
then after main(){}
// function template definition
template
void Swap(Any &a, Any &b)
{
Any temp;
temp = a;
a = b;
b = temp;
}
Note that function templates don't make executable programs any shorter!
The final code does not contain templates; it just contains the actual functions generated for the program. The benefits of templates are that they make generating multiple function definitions simpler and more reliable.
By passing a type as parameter to a template, you cause the compiler to generate a function for that particular type. Because templates let you program in terms of a generic type instead of a specific type, the process is somethimes called generic programming.
Because types are represented by parameters, the template feature is somethimes referred as parameterized types.
Function templates enable you to define a function in terms of some arbitrary type. For example, you can set up a swapping template like this:
template
void Swap(Any &a, Any &b)
{
Any temp;
temp = a;
a = b;
b = temp;
}
The first line specifies that you are setting up a template and you're naming the arbitrary type Any. The keyword template and class are obligatory, except you can use the keyword typename instread of class. Also, you must use the angle brackets. The type name (Any, in this example) is your choice, as long as you follow the usual C++ naming rules; many programmers use simple names such as T. The rest of the code describes the algorithm for swapping two values of type Any. The template does not create any functions. Instead, it provides the compiler with directions about how to define a function. If you want a function to swap ints, then the compiler creates a function following the template pattern, substituting int for Any. Similarly, if you need a function to swap doubles, the compiler follows the template, substituting the double type for Any.
The keyword typename is a recent addition to C++. You can use it instead of the keyword class in this particular context. That is, you can write the template definition this way:
template
void Swap(Any &a, Any &b)
{
Any temp;
temp = a;
a = b;
b = temp;
}
The typename keyword makes it a bit more obvious that the parameter Any represents a type;
however, large libraries of code have already been developed by using the older keyword class. The C++ standard treats the two keywords identically when they are used in this context.
To let the compiler know that you need a particular form of swap function, you just use a function called Swap() in your program. The compiler checks the argument types you use and then generates the corresponding function.
In a program, the template could be used as follows:
template
void Swap(Any &a, Any &b);
then after main(){}
// function template definition
template
void Swap(Any &a, Any &b)
{
Any temp;
temp = a;
a = b;
b = temp;
}
Note that function templates don't make executable programs any shorter!
The final code does not contain templates; it just contains the actual functions generated for the program. The benefits of templates are that they make generating multiple function definitions simpler and more reliable.
Function Overloading
Function polymorphism is a neat C++ addition to C's capabilities. function polymorphism, also called function overloading, lets you use multiple functions sharing the same name.
polymorphism means having many forms.
So function polymorphism lets a function have many forms.
Similarly, the expression function overloading means you can attach more than one function to the same name, thus overloading the name.
You can use function overloading to design a family of functions that do essentially the same thing, but using different argument lists.
Overloaded functions are analogous to verbs having more than one meaning.
The key to function overloading it a function's argument list, also called the function signature.
If two functions use the same number and types of arguments in the same order, they have the same signature. the variable names don't matter.
C++ enables you to define two functions by the same name, provided that the functions have different signatures. The signature can differ in the number of arguments or in the type of arguments, or both. For example you can define a set of print() functions with the following prototypes:
void print(const char * str, int width); // #1
void print(double d, int width); // #2
void print(long l, int width); // #3
void print(int i, int width); // #4
void print(const char * str); // #5
When you use a print() function, the compiler matches your use to the prototype that has the same signature:
print("Pancakes", 15); // use #1
print("Syrup"); // use #5
print(1999.0, 10); // use #2
print(1999, 12); // use #4
print(1999L, 15); // use #3
When to use function overloading?
You might find function overloading fascinating, but you shouldn't overuse it. You should reserve function overloading for functions that perform basically the same task, but with different forms of data. Also you might want to check wether you can accomplish the same end by using default arguments.
char * left(const char * str, unsigned n); // two arguments
char * left(const char * str); // one argument
But using a single function with a default argument is simpler. There's just one function to write, instead of two, and the program requires memory for just one function, instead of two.
If you decide to modify the function, you have to edit only one. However, if you require different types of arguments, default arguments are of no avail, so in that case, you should use function overloading.
How does C++ keep track of which overloaded function is which?
It assigns a secret identity to each of these functions.
When you compile programs, the C++ compiler performs a bit of magic on your behalf--known as name decoration or name mangling--through which each function name is encrypted, based on the formal parameter types specified in the function's prototype. Consider the following undecorated function prototype:
long MyFunctionFoo(int, float);
For its own use, the compiler documents this interface by transforming the name into an internal representation with a more unsightly appearance, perhaps something like this:
?myFunctionFoo@@YAXH@Z
The apperent gibberish decorating the original name(or mangling is, depending on your attitude)
encodes the number and types of parameters. A different function signature would result in a different set of symbols being added, and different compilers would use different conventions for their efforts at decorating.
polymorphism means having many forms.
So function polymorphism lets a function have many forms.
Similarly, the expression function overloading means you can attach more than one function to the same name, thus overloading the name.
You can use function overloading to design a family of functions that do essentially the same thing, but using different argument lists.
Overloaded functions are analogous to verbs having more than one meaning.
The key to function overloading it a function's argument list, also called the function signature.
If two functions use the same number and types of arguments in the same order, they have the same signature. the variable names don't matter.
C++ enables you to define two functions by the same name, provided that the functions have different signatures. The signature can differ in the number of arguments or in the type of arguments, or both. For example you can define a set of print() functions with the following prototypes:
void print(const char * str, int width); // #1
void print(double d, int width); // #2
void print(long l, int width); // #3
void print(int i, int width); // #4
void print(const char * str); // #5
When you use a print() function, the compiler matches your use to the prototype that has the same signature:
print("Pancakes", 15); // use #1
print("Syrup"); // use #5
print(1999.0, 10); // use #2
print(1999, 12); // use #4
print(1999L, 15); // use #3
When to use function overloading?
You might find function overloading fascinating, but you shouldn't overuse it. You should reserve function overloading for functions that perform basically the same task, but with different forms of data. Also you might want to check wether you can accomplish the same end by using default arguments.
char * left(const char * str, unsigned n); // two arguments
char * left(const char * str); // one argument
But using a single function with a default argument is simpler. There's just one function to write, instead of two, and the program requires memory for just one function, instead of two.
If you decide to modify the function, you have to edit only one. However, if you require different types of arguments, default arguments are of no avail, so in that case, you should use function overloading.
How does C++ keep track of which overloaded function is which?
It assigns a secret identity to each of these functions.
When you compile programs, the C++ compiler performs a bit of magic on your behalf--known as name decoration or name mangling--through which each function name is encrypted, based on the formal parameter types specified in the function's prototype. Consider the following undecorated function prototype:
long MyFunctionFoo(int, float);
For its own use, the compiler documents this interface by transforming the name into an internal representation with a more unsightly appearance, perhaps something like this:
?myFunctionFoo@@YAXH@Z
The apperent gibberish decorating the original name(or mangling is, depending on your attitude)
encodes the number and types of parameters. A different function signature would result in a different set of symbols being added, and different compilers would use different conventions for their efforts at decorating.
When to use Reference Arguments
There are two main reasons for using reference arguments:
- To allow you to alter a data object in the calling function
- To speed up a program by passing a reference instead of an entire object
The second is most imporatant for larger data objects, such as structures and class objects.
These two reasons are the same reasons you might have for using a pointer argument.
This makes sense because reference arguments are really just a different initerface for pointer-based code. So when should you use a reference? use a pointer? pass by value? The following are some guidelines.
A function used passed data without modifying it:
- If the data object is small, such as a build-in data type or a small structure, pass it by value.
- If the data object is an array, use pointer because that is your only choice, Make the pointer a pointer to const.
- If the data is a good-sized structure, use a const pointer or a const reference to increase program effficiency. You save time and space needed to copy a structure or a class design. Make the pointer or reference const.
- If the data object is a class object, use a const reference. The semantics of class design often require using a reference, which is the main reason C++ added this feature. Thus, the standard way to pass class object arguments is by reference.
A function modifies data in the calling function:
- If the data object is a built-in data type, use a pointer. If you spot code like fixit(&x), where x is an int, it's pretty clear that this function intents to modify x.
- If the data object is an array, use your only choice: a pointer
- If the data object is a structure, use a reference or a pointer
- If the data object is a class object, use a reference.
Of course, these are just guidelines, and there might be reasons for making different choices.
For example, cin uses references for basic types so that you can use cin >> n instead of cin >> &n.
- To allow you to alter a data object in the calling function
- To speed up a program by passing a reference instead of an entire object
The second is most imporatant for larger data objects, such as structures and class objects.
These two reasons are the same reasons you might have for using a pointer argument.
This makes sense because reference arguments are really just a different initerface for pointer-based code. So when should you use a reference? use a pointer? pass by value? The following are some guidelines.
A function used passed data without modifying it:
- If the data object is small, such as a build-in data type or a small structure, pass it by value.
- If the data object is an array, use pointer because that is your only choice, Make the pointer a pointer to const.
- If the data is a good-sized structure, use a const pointer or a const reference to increase program effficiency. You save time and space needed to copy a structure or a class design. Make the pointer or reference const.
- If the data object is a class object, use a const reference. The semantics of class design often require using a reference, which is the main reason C++ added this feature. Thus, the standard way to pass class object arguments is by reference.
A function modifies data in the calling function:
- If the data object is a built-in data type, use a pointer. If you spot code like fixit(&x), where x is an int, it's pretty clear that this function intents to modify x.
- If the data object is an array, use your only choice: a pointer
- If the data object is a structure, use a reference or a pointer
- If the data object is a class object, use a reference.
Of course, these are just guidelines, and there might be reasons for making different choices.
For example, cin uses references for basic types so that you can use cin >> n instead of cin >> &n.
maandag 25 juni 2007
Objects, Inheritance, and References
The ostream and ofstream classes bring an interesting property of references to the fore.
As you may remember from other things I blogged, objects of the ofstream type can use ostream methods, allowing file input/output to use the same forms as console input/output.
The language feature that makes it possible to pass features from one class to another is called inheritance.
In brief, ostream is termed a base class (because the ofstream class is based on it) and ofstream is termed a derived class(becuase it is derived from ostream). A derived class inherits the base class methods, which means that an ofstream object can use base class features such as the precision() and setf() formatting methods.
Another aspect if inheritance is that a base class reference can refer to a derived class object without requiring a type cast. The practical upshot of this is that you can define a function having a base class reference parameter, and that function can be used with base class objects and also with derived objects. For example, a function with a type ostream & parameter can accept an ostream object, such as cout, or an ofstream object such as you might declare equally well.
As you may remember from other things I blogged, objects of the ofstream type can use ostream methods, allowing file input/output to use the same forms as console input/output.
The language feature that makes it possible to pass features from one class to another is called inheritance.
In brief, ostream is termed a base class (because the ofstream class is based on it) and ofstream is termed a derived class(becuase it is derived from ostream). A derived class inherits the base class methods, which means that an ofstream object can use base class features such as the precision() and setf() formatting methods.
Another aspect if inheritance is that a base class reference can refer to a derived class object without requiring a type cast. The practical upshot of this is that you can define a function having a base class reference parameter, and that function can be used with base class objects and also with derived objects. For example, a function with a type ostream & parameter can accept an ostream object, such as cout, or an ofstream object such as you might declare equally well.
passing a C-Style String to a string object parmeter
string version1(const string & s1, const string & s2)
{
string temp;
temp = s2 + s1 + s2;
return temp;
}
string input;
getline(cin, input);
result = version1(input, "***");
Now the question is, how can it be that the string literal "***" can be passed as it is a string object to the function version1?
The answer has two parts:
1. The string class defines a char * to string conversion.
2. If a actual argument does not match the const reference argument, and the argument can be converted to the correct type, then a temporary variable of the correct type is created, a string in this case, and is used during the existence of the function called.
Earlier you saw that a const double & parameter can handle an int argument in this fashion.
The convenient outcome of this is that if the formal parameter is type const string &, the actual argument used in the function call can be a string object or a C-style string, such as a quoted string literal, a null-terminated array of char, or a pointer variable that points to a char.
Hence, the following works fine:
result = version1(input, "***");
{
string temp;
temp = s2 + s1 + s2;
return temp;
}
string input;
getline(cin, input);
result = version1(input, "***");
Now the question is, how can it be that the string literal "***" can be passed as it is a string object to the function version1?
The answer has two parts:
1. The string class defines a char * to string conversion.
2. If a actual argument does not match the const reference argument, and the argument can be converted to the correct type, then a temporary variable of the correct type is created, a string in this case, and is used during the existence of the function called.
Earlier you saw that a const double & parameter can handle an int argument in this fashion.
The convenient outcome of this is that if the formal parameter is type const string &, the actual argument used in the function call can be a string object or a C-style string, such as a quoted string literal, a null-terminated array of char, or a pointer variable that points to a char.
Hence, the following works fine:
result = version1(input, "***");
why use const with reference return
You might be wondering why a lot of functions you see return a const reference.
Here is an example:
use(looper).used = 10;
Here looper is a structure, and the function use() returns a non-const reference to the structure, as you see this makes it possible to write obscure code, by which you directly modify the returned structure. If the use() function had returned a const reference, then such code was not possible. You might say it is cool to return a non-const reference, because the code can be short, but the book I read says it is obscure to code like this. Think for yourself when creating code.
Another example:
sysop newgal = {"Polly Morf", "Polly's not a hacker.", 0};
use(looper) = newgal;
now looper is a copy from newgal, this kind of code is not what you like.
In short, by omitting const, you can write shorter but more obscure-looking code.
Occasionally omitting const does make sense. The overloaded << operator later discussed is an example.
Here is an example:
use(looper).used = 10;
Here looper is a structure, and the function use() returns a non-const reference to the structure, as you see this makes it possible to write obscure code, by which you directly modify the returned structure. If the use() function had returned a const reference, then such code was not possible. You might say it is cool to return a non-const reference, because the code can be short, but the book I read says it is obscure to code like this. Think for yourself when creating code.
Another example:
sysop newgal = {"Polly Morf", "Polly's not a hacker.", 0};
use(looper) = newgal;
now looper is a copy from newgal, this kind of code is not what you like.
In short, by omitting const, you can write shorter but more obscure-looking code.
Occasionally omitting const does make sense. The overloaded << operator later discussed is an example.
Being carefull what a return reference refers to!
The single most important point to remember when returning a reference is avoid returning a reference to a memory location that ceases to exist when the function terminates!
What you want to avoid is code along these lines:
const sysop & clone2(sysop & sysopref)
{
sysop newguy; // first step to big error
newguy = sysopref; // copy info
return newguy; // return reference to copy
}
This has the unfortunate effect of returning a reference to a temporary variable (newguy) that passes from existence as soon as the function terminates.
Similarly you should avoid returning pointers to such temporary variables.
The simplest way to avoid this problem is to return a reference that was passed as an argument to the function. A reference parameter will refer to data used by the calling function, hence the returned reference will refer to that same data.
A second method is to use new to create new storage.
const sysop & clone(sysop & sysopref)
{
sysop * psysop = new sysop;
*psysop = sysopref; // copy info
return *psysop;
}
The first statement creates a nameless sysop structure. The pointer psysop points to the structure, so *psysop is the structure. The code appears to return the structure, but the function declaration indicates that the function really returns a reference to this structure. You could then use the function this way:
sysop & jolly = clone(looper);
This makes jolly a reference to the new structure. There is a problem with this approach: You should use delete to free memory allocated by new when the memory is no longer needed. A call to clone() hides the call to new, making it simpler to forget to use delete later. The auto_ptr template discussed later can help automate the deletion process.
What you want to avoid is code along these lines:
const sysop & clone2(sysop & sysopref)
{
sysop newguy; // first step to big error
newguy = sysopref; // copy info
return newguy; // return reference to copy
}
This has the unfortunate effect of returning a reference to a temporary variable (newguy) that passes from existence as soon as the function terminates.
Similarly you should avoid returning pointers to such temporary variables.
The simplest way to avoid this problem is to return a reference that was passed as an argument to the function. A reference parameter will refer to data used by the calling function, hence the returned reference will refer to that same data.
A second method is to use new to create new storage.
const sysop & clone(sysop & sysopref)
{
sysop * psysop = new sysop;
*psysop = sysopref; // copy info
return *psysop;
}
The first statement creates a nameless sysop structure. The pointer psysop points to the structure, so *psysop is the structure. The code appears to return the structure, but the function declaration indicates that the function really returns a reference to this structure. You could then use the function this way:
sysop & jolly = clone(looper);
This makes jolly a reference to the new structure. There is a problem with this approach: You should use delete to free memory allocated by new when the memory is no longer needed. A call to clone() hides the call to new, making it simpler to forget to use delete later. The auto_ptr template discussed later can help automate the deletion process.
Reference arguments, use const when you can!
There are three strong reasons to declare reference arguments as references to constant data:
- Using const protects you against programming errors that inadvertently alter data
- Using const allows a function to process both const and non-const actual arguments, whereas a function that omits const in the prototype only can accept non-const data.
- Using a const reference allows the function to generate and use a temporary variable appropriately.
You should declare formal reference arguments as const whenever it's appropriate to do so.
- Using const protects you against programming errors that inadvertently alter data
- Using const allows a function to process both const and non-const actual arguments, whereas a function that omits const in the prototype only can accept non-const data.
- Using a const reference allows the function to generate and use a temporary variable appropriately.
You should declare formal reference arguments as const whenever it's appropriate to do so.
References as Function Parameters
Most often references are used as function parameters, making a variable name in a function an alias for a variable in the calling program.
This method of passing arguments is called: Passing by reference!
Passing by reference allows a called function to access variables in the calling function.
C++'s addition of the feature is break down from C, which only passes by value.
Passing by value, recall, results in the called function working with copies of values from the calling program/function.'Of course, C lets you get arround the passing by value limitation by using pointers.
Using passing by value, if a function has one argument, makes two variables, one the argument and one variable in the function initialized with the value of the argument.
Using passing by reference, if a function has one argument, makes one variable, the argument, and a reference in the function to that variable, which is two names for one variable.
Functions that pass by value, can use many kinds of actual arguments:
double cube(double a)
{
a *= a * a;
return a;
}
double z = cube(x + 2.0); // evaluate x + 2.0, pass value
z = cube(8.0); // pass the value 8.0
int k = 10;
z = cube(k); // convert value of k to double, pass value
double yo[3] = { 2.2, 3.3, 4.4};
z = cube(yo[2]); // pass the value 4.4
Suppose you try similar arguments for a function with a reference parameter:
double refcube(double & ra)
{
ra *= ra * ra;
return ra;
}
It would seem that passing a reference should be more restrictive. After all, if ra is the alternative name for a variable, then the actual arguments should be that variable. Something like:
double z = refcube(x + 3.0); // may not compile
doesn't appear to make sense because the expression x + 3.0 is not a variable. For example you can't assign a value to such expression:
x + 3.0 = 5.0 // nonsensical
In some cases, the compiler will accept x + 3.0.
What happens is that because x + 3.0 is not a type double variable, the program creates a temporary, nameless variable, intializing it to the value of the expression x + 3.0. Then ra becomes a reference to that temporary variable. Let's take a closer look at temporary variables and see when they are and are not created.
C++ can generate a temporary variable if the actual argument doesn't match a reference argument. Currently C++ permits this only if the argument is a const reference, but this is a new restriction.
Provided that the reference parameter is a const, the compiler generates a temporary variable in two kinds of situations:
- When the actual argument is the correct type but isn't a lvalue
- When the actual argument is of the wrong type, but it's of a type that can be converted to the correct type
An argument that is an lvalue is a data object that can be referenced. For example, a variable, an array element, a structure member, a reference, and a dereferenced pointer are lvalues.
Non-lvalues include literal constants and expressions with multiple terms. For example, supose you redifine refcube() so that it has a constant reference argument:
double refcube(const double &ra)
{
return ra * ra * ra;
}
Now consider the following code:
double side = 3.0;
double * pd = &side;
double & rd = side;
long edge = 5L;
double lens[4] = { 2.0, 5.0, 10.0, 12.0};
double c1 = refcube(side); // ra is side
double c2 = refcube(lens[2]); // ra is lens[2]
double c3 = refcube(rd); // ra is rd is side
double c4 = refcube(*pd); // ra is *pd is side
double c5 = refcube(edge); // ra is temporary variable
double c6 = refcube(7.0); // ra is temporary variable
double c7 = refcube(side + 10.0); // ra is temporary variable
The arguments side, lens[2], rd and *pd are type double data objects with names, so it is possible to generate a reference for them, and no temporary variables are needed. (Recall that an element of an array behaves like a variable of the same type as the element.)
But although edge is a variable, it is of the wrong type. A reference to a double can't refer to a long. The arguments 7.0 and side + 10.0, on the otherhand, are the right type, but they are not named data objects. In each of these cases, the compiler generates a temporary, anonymous variable and makes ra refer to it. These temporary variables last for the duration of the function call, but then the compiler is free to dump them.
So why is this behaviour okay for constant references but not otherwise?
void swapr(int & a, int & b) // use references
{
int temp;
temp = a; // use a, b for values of variables
a = b;
b = temp;
}
What would happen if you did the following under the freer rules of early C++?
long a = 3, b = 5;
swapr(a, b);
Here there is a type mismatch, so the compiler would create two temporary int variables, initialize them to 3 and 5, and then swap the contents of the temporary variables, leaving a and b unaltered,
The solution is to prohibit creating temporary variables in these situations, and that is what the C++ standard now does!
Now think about the refcube() function. Its intent is merely to use passed values, not to modify them, so temporary variables cause no harm and make the function more general in the sort of arguments is can handle. Therefor, if the declaration states that a reference is const, C++ generates temporary variables when necessary. In essence, a C++ function with a const reference formal argument and a nonmatching actual argument mimics the traditional passing by value behavior, guaranteeing that the original data is unaltered and using a temporary variable to hold the value.
REMEMBER:
If a function call argument isn't an lvalue or does not match the type of the corresponding const reference parameter, C++ creates an anonymous variable of the correct type, assigns the value of the function call argument to the anonymous variable, and has the parameter refer to that variable.
This method of passing arguments is called: Passing by reference!
Passing by reference allows a called function to access variables in the calling function.
C++'s addition of the feature is break down from C, which only passes by value.
Passing by value, recall, results in the called function working with copies of values from the calling program/function.'Of course, C lets you get arround the passing by value limitation by using pointers.
Using passing by value, if a function has one argument, makes two variables, one the argument and one variable in the function initialized with the value of the argument.
Using passing by reference, if a function has one argument, makes one variable, the argument, and a reference in the function to that variable, which is two names for one variable.
Functions that pass by value, can use many kinds of actual arguments:
double cube(double a)
{
a *= a * a;
return a;
}
double z = cube(x + 2.0); // evaluate x + 2.0, pass value
z = cube(8.0); // pass the value 8.0
int k = 10;
z = cube(k); // convert value of k to double, pass value
double yo[3] = { 2.2, 3.3, 4.4};
z = cube(yo[2]); // pass the value 4.4
Suppose you try similar arguments for a function with a reference parameter:
double refcube(double & ra)
{
ra *= ra * ra;
return ra;
}
It would seem that passing a reference should be more restrictive. After all, if ra is the alternative name for a variable, then the actual arguments should be that variable. Something like:
double z = refcube(x + 3.0); // may not compile
doesn't appear to make sense because the expression x + 3.0 is not a variable. For example you can't assign a value to such expression:
x + 3.0 = 5.0 // nonsensical
In some cases, the compiler will accept x + 3.0.
What happens is that because x + 3.0 is not a type double variable, the program creates a temporary, nameless variable, intializing it to the value of the expression x + 3.0. Then ra becomes a reference to that temporary variable. Let's take a closer look at temporary variables and see when they are and are not created.
C++ can generate a temporary variable if the actual argument doesn't match a reference argument. Currently C++ permits this only if the argument is a const reference, but this is a new restriction.
Provided that the reference parameter is a const, the compiler generates a temporary variable in two kinds of situations:
- When the actual argument is the correct type but isn't a lvalue
- When the actual argument is of the wrong type, but it's of a type that can be converted to the correct type
An argument that is an lvalue is a data object that can be referenced. For example, a variable, an array element, a structure member, a reference, and a dereferenced pointer are lvalues.
Non-lvalues include literal constants and expressions with multiple terms. For example, supose you redifine refcube() so that it has a constant reference argument:
double refcube(const double &ra)
{
return ra * ra * ra;
}
Now consider the following code:
double side = 3.0;
double * pd = &side;
double & rd = side;
long edge = 5L;
double lens[4] = { 2.0, 5.0, 10.0, 12.0};
double c1 = refcube(side); // ra is side
double c2 = refcube(lens[2]); // ra is lens[2]
double c3 = refcube(rd); // ra is rd is side
double c4 = refcube(*pd); // ra is *pd is side
double c5 = refcube(edge); // ra is temporary variable
double c6 = refcube(7.0); // ra is temporary variable
double c7 = refcube(side + 10.0); // ra is temporary variable
The arguments side, lens[2], rd and *pd are type double data objects with names, so it is possible to generate a reference for them, and no temporary variables are needed. (Recall that an element of an array behaves like a variable of the same type as the element.)
But although edge is a variable, it is of the wrong type. A reference to a double can't refer to a long. The arguments 7.0 and side + 10.0, on the otherhand, are the right type, but they are not named data objects. In each of these cases, the compiler generates a temporary, anonymous variable and makes ra refer to it. These temporary variables last for the duration of the function call, but then the compiler is free to dump them.
So why is this behaviour okay for constant references but not otherwise?
void swapr(int & a, int & b) // use references
{
int temp;
temp = a; // use a, b for values of variables
a = b;
b = temp;
}
What would happen if you did the following under the freer rules of early C++?
long a = 3, b = 5;
swapr(a, b);
Here there is a type mismatch, so the compiler would create two temporary int variables, initialize them to 3 and 5, and then swap the contents of the temporary variables, leaving a and b unaltered,
The solution is to prohibit creating temporary variables in these situations, and that is what the C++ standard now does!
Now think about the refcube() function. Its intent is merely to use passed values, not to modify them, so temporary variables cause no harm and make the function more general in the sort of arguments is can handle. Therefor, if the declaration states that a reference is const, C++ generates temporary variables when necessary. In essence, a C++ function with a const reference formal argument and a nonmatching actual argument mimics the traditional passing by value behavior, guaranteeing that the original data is unaltered and using a temporary variable to hold the value.
REMEMBER:
If a function call argument isn't an lvalue or does not match the type of the corresponding const reference parameter, C++ creates an anonymous variable of the correct type, assigns the value of the function call argument to the anonymous variable, and has the parameter refer to that variable.
zondag 24 juni 2007
Reference Variables
A reference is a name that acts as an alias, or an alternative name, for a previously defined variable. Main use for a reference variable is as a formal argument to a function.
If you use a reference as argument, the function works with the ORIGINAL data instead of with a copy. References provide a convinient alternative to pointers for processing large structures with a function, and they are essential for designing classes.
You might recall that C and C++ use the & symbol to indicate the address of a variable. C++ assigns an additional meaning to the & symbol and presses it into service for declaring references.
For example, to make rodents an alternative name for the variable rats, you could do the following:
int rats;
int & rodents = rats; // makes rodents an alias for rats
In this context, & is not the address operator. Instead, it serves as part of the type identifier.
Just as char * in a declaration means pointer-to-char, int & means reference-to-int.
The reference declaration allows you to use rats and rodents interchangeably;
both refer to the same value and the same memory location.
Note that the & in int & rodents = rats; is not the address operator, but makes rodents of type int &, that is a reference to an int variable!
cout << ", rodents address = " << &rodents << endl;
Now in the example above & is used as address operator!
It is necessary to initialize the reference when you declare it; you can't declare the reference and then assign it a value later the way you can with a pointer.
int rat;
int & rodent;
rodent = rat; // No, you can't do this.!
rodent = rats;
Does not mean to make rodent a reference to rats, but copies the value of rats to rodent, also changing rat to that value.
In short, you can set a reference by an initializing declaration, not by assignment!
Suppose you tried the following:
int rats = 101;
int * pt = &rats;
int & rodents = *pt;
int bunnies = 50;
pt = &bunnies;
Initializing rodents to *pt makes rodents refer to rats. Subsequentely altering pt to point to bunnies does not alter the fact that rodents refers to rats.
If you use a reference as argument, the function works with the ORIGINAL data instead of with a copy. References provide a convinient alternative to pointers for processing large structures with a function, and they are essential for designing classes.
You might recall that C and C++ use the & symbol to indicate the address of a variable. C++ assigns an additional meaning to the & symbol and presses it into service for declaring references.
For example, to make rodents an alternative name for the variable rats, you could do the following:
int rats;
int & rodents = rats; // makes rodents an alias for rats
In this context, & is not the address operator. Instead, it serves as part of the type identifier.
Just as char * in a declaration means pointer-to-char, int & means reference-to-int.
The reference declaration allows you to use rats and rodents interchangeably;
both refer to the same value and the same memory location.
Note that the & in int & rodents = rats; is not the address operator, but makes rodents of type int &, that is a reference to an int variable!
cout << ", rodents address = " << &rodents << endl;
Now in the example above & is used as address operator!
It is necessary to initialize the reference when you declare it; you can't declare the reference and then assign it a value later the way you can with a pointer.
int rat;
int & rodent;
rodent = rat; // No, you can't do this.!
rodent = rats;
Does not mean to make rodent a reference to rats, but copies the value of rats to rodent, also changing rat to that value.
In short, you can set a reference by an initializing declaration, not by assignment!
Suppose you tried the following:
int rats = 101;
int * pt = &rats;
int & rodents = *pt;
int bunnies = 50;
pt = &bunnies;
Initializing rodents to *pt makes rodents refer to rats. Subsequentely altering pt to point to bunnies does not alter the fact that rodents refers to rats.
inline functions
The compiler replaces the function call with the corresponding function code, instead of saving the return address, the address of the next instruction after the function call, and also the compiler does not store local variables on the stack. It places the function code inline with the other code.
With inline code, the program doesn' have to jump to another location to execute the code and then jump back.
Inline functions thus run a little faster than regular functions, but they come with a memory penalty.
If a program calls an inline function at 10 separate locations, then the program consists of 10 copies of the function inserted into code.
Recursion is not allowed for inline functions.
C users did make inline functions with macro's, one problem is with that that the functions are just expanded text, so no type checking is enforced by the compiler.
With inline code, the program doesn' have to jump to another location to execute the code and then jump back.
Inline functions thus run a little faster than regular functions, but they come with a memory penalty.
If a program calls an inline function at 10 separate locations, then the program consists of 10 copies of the function inserted into code.
Recursion is not allowed for inline functions.
C users did make inline functions with macro's, one problem is with that that the functions are just expanded text, so no type checking is enforced by the compiler.
zaterdag 23 juni 2007
Function Pointer, Pointer to Function.
To implement pointers to functions, you need to be able to do the following:
- Obtain the address of a function
- Declare a pointer to a function
- Use a pointer to a function to invoke the function
Obtaining the address of a function is simple, You just use the function name without trailing parentheses. That is, if think() is a function, then think is the address of the function.
Be sure you distinguish between passing the address of a function and passing the return value of a function:
process(think); // passes address of think() to process()
thought(think()); // passes return value of think() to thought()
Declaring a Pointer to a Function
The declaration of a pointer to a function should identify the function's return type and the function's signature (its argument list).
That is, the declaration of a pointer to a function should provide the same information about a function that a function prototype does. For example:
double pam(int); // prototype
Here's what a declaration of an approriate pointer type looks like:
double (*pf)(int); // pf points to a function that takes
// one int argument and that
// returns type double
Note that this looks just like the pam() declaration, with (*pf) playing the part of pam. Because pam is a function, so is (*pf). and if (*pf) is a function, then pf is a pointer to a function.
Tip:
In general, to declare a pointer to a particular kind of function, you can first write the prototype for a regular function if the desired kind, and then replace the function name with an expression in the form of (*pf). In this case, pf is a pointer to a function of that type.
The declaration requires the parentheses arround *pf to provide the proper operator precedence. Parentheses have a higher precedence than the * operator, so *pf(int) means pf() is a function that returns a pointer, whereas (*pf)(int) means pf is a pointer to a function:
double (*pf)(int); // pf points to a function that returns a double
double *pf(int); // pf() a function that returns a pointer-to-double
After you declare pf properly, you can assign to it the address of a matching function:
double pam(int);
double (*pf)(int);
pf = pam; // pf now points to the pam() function
Note that pam() has to match pf int both signature and return type. The compiler rejects non-matching assignments:
double ned(double);
int ted(int);
double (*pf)(int);
pf = ned; // invalid -- mismatched signature
pf = ted; // invalid -- mismatched return type
Example of a function declaration of a function that takes a function address as parameter:
void estimate(int lines, double (*pf)(int));
This declaration says the second argument is a pointer to a function that has an int argument and a double return value. To have estimate() use the pam() function, you pass pam()'s address to it:
estimate(50, pam); // function call telling estimate() to use pam()
Clearly, the tricky part about using pointers to functions is writing the prototypes, whereas passing the address is very simple.
Using a Pointer to Invoke a Function
Now we get to the final part of the technique, which is using a pointer to call the pointed-to-function. The clue comes in the pointer declaration. There, recall, (*pf) plays the same role as a function name. Thus, all you have to do is use (*pf) as if it were a function name:
double pam(int);
double (*pf)(int);
pf = pam; // pf now points to the pam() function
double x = pam(4); // call pam() using the function name
double y = (*pf)(5); // call pam() using the pointer pf
Actually, C++ also allows you to use pf as if it where a function name:
double y = pf(5); // also call pam() using the pointer pf
Using the first form is uglier, but provides a strong visual reminder that the code is using a function pointer.
/////////////////
Holy syntax! How can pf and (*pf) be equivalent?
a function name is an address concerned to C++ compiler,
func1(); to call it, where func1 is the address of func one, so it is dereferenced
automatically.
(*func1)(); dereference the function also, but now visible very much.
*func1(); will not dereference, but instead call func1() and then try to dereference the result, see this
* func1(); you see?
- Obtain the address of a function
- Declare a pointer to a function
- Use a pointer to a function to invoke the function
Obtaining the address of a function is simple, You just use the function name without trailing parentheses. That is, if think() is a function, then think is the address of the function.
Be sure you distinguish between passing the address of a function and passing the return value of a function:
process(think); // passes address of think() to process()
thought(think()); // passes return value of think() to thought()
Declaring a Pointer to a Function
The declaration of a pointer to a function should identify the function's return type and the function's signature (its argument list).
That is, the declaration of a pointer to a function should provide the same information about a function that a function prototype does. For example:
double pam(int); // prototype
Here's what a declaration of an approriate pointer type looks like:
double (*pf)(int); // pf points to a function that takes
// one int argument and that
// returns type double
Note that this looks just like the pam() declaration, with (*pf) playing the part of pam. Because pam is a function, so is (*pf). and if (*pf) is a function, then pf is a pointer to a function.
Tip:
In general, to declare a pointer to a particular kind of function, you can first write the prototype for a regular function if the desired kind, and then replace the function name with an expression in the form of (*pf). In this case, pf is a pointer to a function of that type.
The declaration requires the parentheses arround *pf to provide the proper operator precedence. Parentheses have a higher precedence than the * operator, so *pf(int) means pf() is a function that returns a pointer, whereas (*pf)(int) means pf is a pointer to a function:
double (*pf)(int); // pf points to a function that returns a double
double *pf(int); // pf() a function that returns a pointer-to-double
After you declare pf properly, you can assign to it the address of a matching function:
double pam(int);
double (*pf)(int);
pf = pam; // pf now points to the pam() function
Note that pam() has to match pf int both signature and return type. The compiler rejects non-matching assignments:
double ned(double);
int ted(int);
double (*pf)(int);
pf = ned; // invalid -- mismatched signature
pf = ted; // invalid -- mismatched return type
Example of a function declaration of a function that takes a function address as parameter:
void estimate(int lines, double (*pf)(int));
This declaration says the second argument is a pointer to a function that has an int argument and a double return value. To have estimate() use the pam() function, you pass pam()'s address to it:
estimate(50, pam); // function call telling estimate() to use pam()
Clearly, the tricky part about using pointers to functions is writing the prototypes, whereas passing the address is very simple.
Using a Pointer to Invoke a Function
Now we get to the final part of the technique, which is using a pointer to call the pointed-to-function. The clue comes in the pointer declaration. There, recall, (*pf) plays the same role as a function name. Thus, all you have to do is use (*pf) as if it were a function name:
double pam(int);
double (*pf)(int);
pf = pam; // pf now points to the pam() function
double x = pam(4); // call pam() using the function name
double y = (*pf)(5); // call pam() using the pointer pf
Actually, C++ also allows you to use pf as if it where a function name:
double y = pf(5); // also call pam() using the pointer pf
Using the first form is uglier, but provides a strong visual reminder that the code is using a function pointer.
/////////////////
Holy syntax! How can pf and (*pf) be equivalent?
a function name is an address concerned to C++ compiler,
func1(); to call it, where func1 is the address of func one, so it is dereferenced
automatically.
(*func1)(); dereference the function also, but now visible very much.
*func1(); will not dereference, but instead call func1() and then try to dereference the result, see this
* func1(); you see?
vrijdag 22 juni 2007
Recursion
A C++ function has the interesting characteristic that it can call itself. (Unlike C, however C++ does not let main() call itself.) This ability is termed recursion. Recursion is an important tool in certain types of programming, such as artificial intelligengence, but we'll just take a superficial look (artificial shallowness) at how it works.
Recursion with a Single Recursive Call
If a recursive function calls itself, then the newly called function calls itself, and so on, ad infinitum unless the code includes something to terminate the chain of calls. The usual method is to make the recursive call part of an if statement. For example, a type void recursive function called recurs() can have a form like this:
void recurs(argumentlist)
{
statements1
if (test)
recurs(arguments)
statements2
}
With luck or foresight, test eventually becomes false, and the chains of calls is broken.
Recursive calls produce an intriguing chain of events. As long as the if statement remains true, each call to recurs() executes statements1 and then invokes a new incarnation of recurs() without reaching statements2. When the if statement becomes false, the current call then proceeds to statements2. Then when the current call terminates, program control returns to the previous version of recurs() that called it. Then, that version of recurs() completes executing its statements2 section and terminates, returning control to the prior call, and so on. Thus, if recurs() undergoes five recursive calls, first the statements1 section is executed five times in the order in which the functions where called, and then the statements2 section is executed five times in the opposite order from the order in which the were called. After going into five levels of recursion, the program then has to go back out through the same five levels.
Recursion with a Single Recursive Call
If a recursive function calls itself, then the newly called function calls itself, and so on, ad infinitum unless the code includes something to terminate the chain of calls. The usual method is to make the recursive call part of an if statement. For example, a type void recursive function called recurs() can have a form like this:
void recurs(argumentlist)
{
statements1
if (test)
recurs(arguments)
statements2
}
With luck or foresight, test eventually becomes false, and the chains of calls is broken.
Recursive calls produce an intriguing chain of events. As long as the if statement remains true, each call to recurs() executes statements1 and then invokes a new incarnation of recurs() without reaching statements2. When the if statement becomes false, the current call then proceeds to statements2. Then when the current call terminates, program control returns to the previous version of recurs() that called it. Then, that version of recurs() completes executing its statements2 section and terminates, returning control to the prior call, and so on. Thus, if recurs() undergoes five recursive calls, first the statements1 section is executed five times in the order in which the functions where called, and then the statements2 section is executed five times in the opposite order from the order in which the were called. After going into five levels of recursion, the program then has to go back out through the same five levels.
-> the indirect membership operator
If you use a pointer to a struct, you can't use the membership operator, the dot
struct xy
{
int x;
int y;
}
now create a structure
xy aPos;
aPos.x = 10;
aPos.y = 20;
But when using a pointer to the struct:
xy * pxyPos;
pxyPos = &aPos;
You have to use the indirect membership operator
pxyPos->x = 20;
pxyPos->y = 30;
struct xy
{
int x;
int y;
}
now create a structure
xy aPos;
aPos.x = 10;
aPos.y = 20;
But when using a pointer to the struct:
xy * pxyPos;
pxyPos = &aPos;
You have to use the indirect membership operator
pxyPos->x = 20;
pxyPos->y = 30;
arr[i] and &arr[i]
arr[i] == *(arr + i) // values in two notations
&arr[i] == arr + i // addresses in two notations
Remember that adding one to a pointer, including an array name, actually adds a value equal to the size, in bytes, of the type to which the pointer points.
Pointer addition and array subscription are two equivalent ways of counting elements from the beginning of an array.
&arr[i] == arr + i // addresses in two notations
Remember that adding one to a pointer, including an array name, actually adds a value equal to the size, in bytes, of the type to which the pointer points.
Pointer addition and array subscription are two equivalent ways of counting elements from the beginning of an array.
donderdag 21 juni 2007
Pointers
A pointer is a value that represents the address of an object. Every distinct object has a unique address, which denotes the part of the computer's memory that contains the object. If you can access an object, you can obtain its address, and vice versa, so if we have an address we can access the object.
For example if x is an object, then &x is the address of that object, and if p is the address of an object, then *p is the object itself. The & in &x is an address operator, and is distinct from the use of & to define reference types. The * is a dereference operator, which works analogously to the way * works when applied to another iterator. If p contains the address of x, we also say that p is a pointer that points to x. It is common to represent such a state of affairs with a diagram such as:
p---->x
As with other built-in types, a local variable that is a pointer has no meaningful value until we give it one. Programmers frequently use the value 0 to initialize pointers, because converting 0 to a pointer yields a value that is guaranteed to be distinct from a pointer to any object. Moreover, the constant 0 is the only integer value that can be converted to a pointer type. The resulting value, often called a null pointer, is often useful in comparisons.
As with all C++ values, pointers have types. The address of an object of type T has type "pointer to T", written as T* in definitions and similar contexts.
Suppose that x us an object of type int, defined as
int x;
and we want to define p to have a type that will allow p to contain the address of x. We do so by saying that the type of p is "pointer to int", which we say implicitly by defining *p to have type int:
int *p; // *p has type int
Here *p is a declarator, which is the part of a definition that defines a single variable. Even though the * and the p are part of a single declarator, most C++ programmers write this definition as:
int* p; // p has type int
to emphasize the notion that p has a particular type (i.e, int*). These uses are equivalent because the spaces around the * are neutral. However the latter usage conceals a pitfall that is so important that it deserves special attention:
int* p, q; // what does this definition mean?
defines p as an object of type "pointer to int", and q as an object of type int. This example is easier to understand if we view it this way:
int *p, q;
or int (*p), q;
Still better, we can make our intentions crystal clear by writing
int* p;
int q;
We now know enough to write a simple program that uses pointers:
int main()
{
int x = 5;
// p points to x
int* p = &x;
cout << "x = " << p =" 6;" x =" " x =" 5" x =" 6">5
It should be no surprise that x is 5 when we execute the first output expression. The next statement changes the value of x to 6 by executing *p = 6. Remember, once p contains the address of x, *p and x are two different ways of referring to the same object. Thus, the x is 6 when the second output expression is executed.
It may be useful to think of a pointer to an object as an iterator that refers to the only element of a "container" that contains the object and nothing else.
Arrays
An array is a kind of container that is part of the core language rather then part of the standard library. Every array contains a sequence of one or more objects of the same type. The number of elements in the array must be known at compile time, which requirement implies that arrays cannot grow or shrink dynamically the way the library containers do.
Because arrays are not class types, they have no members. In particular the do not have the size_type member to name an appropriate type to deal with the size of an array. Instead, theheader defines size_t, which is a more general type. The implementation defines size_t as the appropriate unsigned type large enough to hold the size of any object. Thus, we can (and should) use size_type to deal with the size of a container.
For example, a three dimensional geometry program might represent a point this way:
double coords[3];
knowing that the number of dimensions in physical space is unlike to change any time soon. A more experienced programmer might represent the point this way:
const size_t NDim = 3;
double coords[NDim];
taking advances, for documentation purposes, of the fact that the value of NDim is known at compilation time (because it is a const size_t that is initialized from a constant). Using NDim instead of 3 distinguishes the 3 that represents the number of dimensions from a 3 that represents, say the number of sides in a triangle.
For example if x is an object, then &x is the address of that object, and if p is the address of an object, then *p is the object itself. The & in &x is an address operator, and is distinct from the use of & to define reference types. The * is a dereference operator, which works analogously to the way * works when applied to another iterator. If p contains the address of x, we also say that p is a pointer that points to x. It is common to represent such a state of affairs with a diagram such as:
p---->x
As with other built-in types, a local variable that is a pointer has no meaningful value until we give it one. Programmers frequently use the value 0 to initialize pointers, because converting 0 to a pointer yields a value that is guaranteed to be distinct from a pointer to any object. Moreover, the constant 0 is the only integer value that can be converted to a pointer type. The resulting value, often called a null pointer, is often useful in comparisons.
As with all C++ values, pointers have types. The address of an object of type T has type "pointer to T", written as T* in definitions and similar contexts.
Suppose that x us an object of type int, defined as
int x;
and we want to define p to have a type that will allow p to contain the address of x. We do so by saying that the type of p is "pointer to int", which we say implicitly by defining *p to have type int:
int *p; // *p has type int
Here *p is a declarator, which is the part of a definition that defines a single variable. Even though the * and the p are part of a single declarator, most C++ programmers write this definition as:
int* p; // p has type int
to emphasize the notion that p has a particular type (i.e, int*). These uses are equivalent because the spaces around the * are neutral. However the latter usage conceals a pitfall that is so important that it deserves special attention:
int* p, q; // what does this definition mean?
defines p as an object of type "pointer to int", and q as an object of type int. This example is easier to understand if we view it this way:
int *p, q;
or int (*p), q;
Still better, we can make our intentions crystal clear by writing
int* p;
int q;
We now know enough to write a simple program that uses pointers:
int main()
{
int x = 5;
// p points to x
int* p = &x;
cout << "x = " << p =" 6;" x =" " x =" 5" x =" 6">5
It should be no surprise that x is 5 when we execute the first output expression. The next statement changes the value of x to 6 by executing *p = 6. Remember, once p contains the address of x, *p and x are two different ways of referring to the same object. Thus, the x is 6 when the second output expression is executed.
It may be useful to think of a pointer to an object as an iterator that refers to the only element of a "container" that contains the object and nothing else.
Arrays
An array is a kind of container that is part of the core language rather then part of the standard library. Every array contains a sequence of one or more objects of the same type. The number of elements in the array must be known at compile time, which requirement implies that arrays cannot grow or shrink dynamically the way the library containers do.
Because arrays are not class types, they have no members. In particular the do not have the size_type member to name an appropriate type to deal with the size of an array. Instead, the
For example, a three dimensional geometry program might represent a point this way:
double coords[3];
knowing that the number of dimensions in physical space is unlike to change any time soon. A more experienced programmer might represent the point this way:
const size_t NDim = 3;
double coords[NDim];
taking advances, for documentation purposes, of the fact that the value of NDim is known at compilation time (because it is a const size_t that is initialized from a constant). Using NDim instead of 3 distinguishes the 3 that represents the number of dimensions from a 3 that represents, say the number of sides in a triangle.
woensdag 20 juni 2007
Functions and Two-Dimensional Arrays
To write a function that has a two-dimensional array as argument, you need to remember that the name of an array is treated as its address, so the corresponding formal parameter is a pointer, just as for one-dimensional arrays. The tricky part is declaring the pointer correctly.
Suppose, for example, that you start with this code:
int data[3][4] = {{1,2,3,4}, {9,8,7,6}, {2,4,6,8}};
int total = sum(data, 3);
What should the prototype for sum() look like? And why does the function pass the number of rows (3) as an argument and not also the number of columns(4)?
Well, data is the name of an array with three elements. The first element is, itself, an array of four int values. Thus, the type of data is pointer-to-array-of-four-int, so an appropiate prototype would be this:
int sum(int (*ar2)[4], int size);
The parentheses are needed because the declaration
int *ar2[4]
Would declare an array of four pointers-to-int instead of a singe pointer-to-array-of-four-int, and a function parameter cannot be an array.
There's an alternative format that means exactly the same thing as this first prototype, but perhaps it is easier to read:
int sum(int ar2[][4], int size);
Either prototype states that ar2 is a pointer, not an array. Also note that the pointer type specifically says it points to an array of four ints. Thus, the pointer type specifies the numbert of columns, which is why the number of columns is not passed as a separate function argument.
Because the pointer type specifies the number of columns, the sum() function only works with arrays with four columns, But the number of rows is specified by the variable size, so sum() can work with a variying number of rows:
int a[100][4];
int b[6][4];
...
int total1 = sum(a, 100); // sum all of a
int total2 = sum(b, 6); // sum all of b
int total3 = sum(a, 10); // sum first 10 rows of a
int total4 = sum(a+10, 20); // sum next 20 rows of a
given that the parameter ar2 is a pointer to an array, how do you use it in the function definition? The simplest way is to use ar2 as if it where the name of a two-dimensional array, Here's a possible function definition:
int sum(int ar2[][4], int size)
{
int total = 0;
for (int r = 0; r < size; r++)
for (int c = 0; c < 4; c++)
total += ar2[r][c];
return total;
}
Again, note that the number of rows is whatever is passed to the size parameter, but the number of columns is fixed at four, both in the parameter declaration for ar2 and in the inner for loop.
Here is why you can use array notation. Because ar2 points to the first element(element 0) of an array whose elements are array-of-four-int, the expression ar2 + r points to the element number r. Therefor ar2[r] is element number r. That element is itself an array-of-four-int, so ar2[r] is the name of that array-of-four-int. Applying a subscript to an array name gives an array element, so ar2[r][c] is an element of the array-of-four-int, hence is a single int value.
The pointer ar2 has to be dereferenced twice to get the data. The simplest way is to use the brackets twice, as in ar2[r][c]. But it is possible, if ungainly, to use the * operator twice:
ar2[r][c] == *(*(ar2 + r) + c) // same thing
To understand this, you can work out the meaning of the subexpressions from inside out:
ar2 // pointer to first row of an array of 4 int
ar2 + r // pointer to row r (an array of 4 int)
*(ar2 + r) // row r (an array of 4 int, hence the name of an array,
// thus a pointer to the first int in the row, i.e., ar2[r]
*(ar2 +r) + c // pointer int number c in row r, i.e., ar2[r] + c
*(*ar2 + r) + c // value of int number c in row r, i.e. ar2[r][c]
Incidentally, the code for sum() does not use const in declaring the parameter ar2 because that technique is for pointers to fundamental types, and ar2 is a pointer to a pointer.
Suppose, for example, that you start with this code:
int data[3][4] = {{1,2,3,4}, {9,8,7,6}, {2,4,6,8}};
int total = sum(data, 3);
What should the prototype for sum() look like? And why does the function pass the number of rows (3) as an argument and not also the number of columns(4)?
Well, data is the name of an array with three elements. The first element is, itself, an array of four int values. Thus, the type of data is pointer-to-array-of-four-int, so an appropiate prototype would be this:
int sum(int (*ar2)[4], int size);
The parentheses are needed because the declaration
int *ar2[4]
Would declare an array of four pointers-to-int instead of a singe pointer-to-array-of-four-int, and a function parameter cannot be an array.
There's an alternative format that means exactly the same thing as this first prototype, but perhaps it is easier to read:
int sum(int ar2[][4], int size);
Either prototype states that ar2 is a pointer, not an array. Also note that the pointer type specifically says it points to an array of four ints. Thus, the pointer type specifies the numbert of columns, which is why the number of columns is not passed as a separate function argument.
Because the pointer type specifies the number of columns, the sum() function only works with arrays with four columns, But the number of rows is specified by the variable size, so sum() can work with a variying number of rows:
int a[100][4];
int b[6][4];
...
int total1 = sum(a, 100); // sum all of a
int total2 = sum(b, 6); // sum all of b
int total3 = sum(a, 10); // sum first 10 rows of a
int total4 = sum(a+10, 20); // sum next 20 rows of a
given that the parameter ar2 is a pointer to an array, how do you use it in the function definition? The simplest way is to use ar2 as if it where the name of a two-dimensional array, Here's a possible function definition:
int sum(int ar2[][4], int size)
{
int total = 0;
for (int r = 0; r < size; r++)
for (int c = 0; c < 4; c++)
total += ar2[r][c];
return total;
}
Again, note that the number of rows is whatever is passed to the size parameter, but the number of columns is fixed at four, both in the parameter declaration for ar2 and in the inner for loop.
Here is why you can use array notation. Because ar2 points to the first element(element 0) of an array whose elements are array-of-four-int, the expression ar2 + r points to the element number r. Therefor ar2[r] is element number r. That element is itself an array-of-four-int, so ar2[r] is the name of that array-of-four-int. Applying a subscript to an array name gives an array element, so ar2[r][c] is an element of the array-of-four-int, hence is a single int value.
The pointer ar2 has to be dereferenced twice to get the data. The simplest way is to use the brackets twice, as in ar2[r][c]. But it is possible, if ungainly, to use the * operator twice:
ar2[r][c] == *(*(ar2 + r) + c) // same thing
To understand this, you can work out the meaning of the subexpressions from inside out:
ar2 // pointer to first row of an array of 4 int
ar2 + r // pointer to row r (an array of 4 int)
*(ar2 + r) // row r (an array of 4 int, hence the name of an array,
// thus a pointer to the first int in the row, i.e., ar2[r]
*(ar2 +r) + c // pointer int number c in row r, i.e., ar2[r] + c
*(*ar2 + r) + c // value of int number c in row r, i.e. ar2[r][c]
Incidentally, the code for sum() does not use const in declaring the parameter ar2 because that technique is for pointers to fundamental types, and ar2 is a pointer to a pointer.
Pointers and const
Using const with pointers has some subtle aspects (pointers always seem to have subtle aspects), so let's take a closer look.
You can use the const keyword two different ways with pointers. The first way is to make a pointer point to a constant object, and that prevents you from using the pointer to change the pointed-to value. The second way is to make the pointer itself a constant, and that prevents you from changing where the pointer points.
First, let's declare a pointer pt that points to a constant:
int age = 39;
const int * pt = &age;
This declaration states that pt points to a const int(39, in this case). Therefor, you can't use pt to change that value. In other words, the value *pt is const and cannot be modified:
*pt += 1; // INVALID because pt points to a const int
cin >> *pt; // INVALID for the same reason
Now for a subtle point. This declaration for pt doesn't necessarily mean that the value it points to is really a constant; it just means the value is a constant insofar as pt is concerned.
For example, pt points to age, and age is not const. You can change the value of age directly by using the age variable, but you can't change the value indirectly via the pt pointer:
*pt = 20; // INVALID because pt points to a const int
age = 20; // VALID because age is not declared to be const
In the past, you've assigned the address of a regular variable to a regular pointer. Now you've assigned the address of a regular variable to a pointer-to-const. That leaves two other possibilities: assigning the address of a const variable to a pointer-to-const and assigning the address of a const to a regular pointer. Are they both possible? The first is, and the second isn't:
const float g_earth = 9.80;
const float * pe = &g_earth; // VALID
const float g_moon = 1.63;
float * pm = &g_moon; // INVALID
For the first case, you can use neither g_earth nor pe to change the value 9.80. C++ doesn't allow the second case for a simple reason: If you assign the address of g_moon to pm, then you can cheat and use pm to alter the value of g_moon.
That makes a mockery of g_moon's const status, so C++ prohibits you from assigning the address of a const to a non-const pointer.
(if you are really desperate, you can use a type cast to override the restriction; see const_cast operator)
The situation becomes a bit more complex if you have pointers to pointers. As you saw earlier, assigning a non-const pointer to a const pointer is okay, provided that you're dealing with just one level of indirection:
int age = 39; // age++ is a valid operation
int * pd = &age; // *pd = 41 is a valid operation
const int * pt = pd; // *pt = 42 is an INVALID operation
But pointer assignments that mix const and non-const in this manner are NO longer SAFE when you go to two levels of indirection. If mixing const and non-const were allowed, you could do something like this:
const int **pp2;
int *p1;
const int n = 13;
pp2 = &p1; // not allowed, but suppose it were
*pp2 = &n; // valid, both const, but sets p1 to point at n
*p1 = 10; // valid, but changes const n
Suppose you have an array of const data:
const int months[12] = {31,28,31,30,31,,30,31,31,30,31,30,31};
The prohibition against assigning the address of a constant array means that you cannot pass the array name as an argument to a function by using a non-const formal argument:
int sum(int arr[], int n); // should have been const int arr[]
...
int j = sum(months, 12); // NOT allowed
This function call attempts to assign a const pointer (months) to a non-const pointer (arr), and the compiler disallows the function call.
Using const When You Can
There are two strong reasons to declare pointer arguments as pointers to constant data:
- It protects you against programming errors that inadvertently alter data
- Using const allows a function to process both const and non-const actual arguments, whereas a function that omits const in the prototype can accept
only non-const data.
You should declare formal pointer arguments as pointers to const whenever it's appropriate to do so.
For yet another subtle point, consider the following declarations:
int age = 39;
const int * pt = &age;
The const in the second declaration only prevents you from changing the value to which pt points, which is 39. It does not prevent you from changing the value of pt itself. That is, you can assign a new value to pt:
int sage = 80;
pt = &sage; // okay to point to another location'
But you still can't use pt to change the value to which it points(now 80)
The second way to use const makes it impossible to change the value of the pointer itself:
int sloth = 3;
const int * ps = &sloth; // a pointer to const int
int * const finger = &sloth; a const pointer to int
Note that the last declaration has repositioned the keyword const. This form of declaration constrains finger to point only to sloth. However, it allows you to use finger to alther the value of sloth. The middle declaration does not allow you to use ps to alter the value of sloth, but it permits you to have ps point to another location. In short, finger and *ps are both const, and *finger and ps are not const.
If you like, you can declare a const pointer to a const object:
double trouble = 2.0E30;
const double * const stick = &trouble;
Here stick can point only to trouble, and stick cannot be used to change the value of trouble. In short both stick and *stick are const.
Typically you use the pointer to const form to protect data when you pass pointers as function arguments. For example:
void show_array(const double ar[], int n);
Using const in this declaration means that show_array() cannot alter the values in any array that is passed to it. This technique works as long as there is just one level of indirection. Here for example, the array elements are fundamental type, but if they where pointers or pointers-to-pointers, you wouldn't use const.
You can use the const keyword two different ways with pointers. The first way is to make a pointer point to a constant object, and that prevents you from using the pointer to change the pointed-to value. The second way is to make the pointer itself a constant, and that prevents you from changing where the pointer points.
First, let's declare a pointer pt that points to a constant:
int age = 39;
const int * pt = &age;
This declaration states that pt points to a const int(39, in this case). Therefor, you can't use pt to change that value. In other words, the value *pt is const and cannot be modified:
*pt += 1; // INVALID because pt points to a const int
cin >> *pt; // INVALID for the same reason
Now for a subtle point. This declaration for pt doesn't necessarily mean that the value it points to is really a constant; it just means the value is a constant insofar as pt is concerned.
For example, pt points to age, and age is not const. You can change the value of age directly by using the age variable, but you can't change the value indirectly via the pt pointer:
*pt = 20; // INVALID because pt points to a const int
age = 20; // VALID because age is not declared to be const
In the past, you've assigned the address of a regular variable to a regular pointer. Now you've assigned the address of a regular variable to a pointer-to-const. That leaves two other possibilities: assigning the address of a const variable to a pointer-to-const and assigning the address of a const to a regular pointer. Are they both possible? The first is, and the second isn't:
const float g_earth = 9.80;
const float * pe = &g_earth; // VALID
const float g_moon = 1.63;
float * pm = &g_moon; // INVALID
For the first case, you can use neither g_earth nor pe to change the value 9.80. C++ doesn't allow the second case for a simple reason: If you assign the address of g_moon to pm, then you can cheat and use pm to alter the value of g_moon.
That makes a mockery of g_moon's const status, so C++ prohibits you from assigning the address of a const to a non-const pointer.
(if you are really desperate, you can use a type cast to override the restriction; see const_cast operator)
The situation becomes a bit more complex if you have pointers to pointers. As you saw earlier, assigning a non-const pointer to a const pointer is okay, provided that you're dealing with just one level of indirection:
int age = 39; // age++ is a valid operation
int * pd = &age; // *pd = 41 is a valid operation
const int * pt = pd; // *pt = 42 is an INVALID operation
But pointer assignments that mix const and non-const in this manner are NO longer SAFE when you go to two levels of indirection. If mixing const and non-const were allowed, you could do something like this:
const int **pp2;
int *p1;
const int n = 13;
pp2 = &p1; // not allowed, but suppose it were
*pp2 = &n; // valid, both const, but sets p1 to point at n
*p1 = 10; // valid, but changes const n
Suppose you have an array of const data:
const int months[12] = {31,28,31,30,31,,30,31,31,30,31,30,31};
The prohibition against assigning the address of a constant array means that you cannot pass the array name as an argument to a function by using a non-const formal argument:
int sum(int arr[], int n); // should have been const int arr[]
...
int j = sum(months, 12); // NOT allowed
This function call attempts to assign a const pointer (months) to a non-const pointer (arr), and the compiler disallows the function call.
Using const When You Can
There are two strong reasons to declare pointer arguments as pointers to constant data:
- It protects you against programming errors that inadvertently alter data
- Using const allows a function to process both const and non-const actual arguments, whereas a function that omits const in the prototype can accept
only non-const data.
You should declare formal pointer arguments as pointers to const whenever it's appropriate to do so.
For yet another subtle point, consider the following declarations:
int age = 39;
const int * pt = &age;
The const in the second declaration only prevents you from changing the value to which pt points, which is 39. It does not prevent you from changing the value of pt itself. That is, you can assign a new value to pt:
int sage = 80;
pt = &sage; // okay to point to another location'
But you still can't use pt to change the value to which it points(now 80)
The second way to use const makes it impossible to change the value of the pointer itself:
int sloth = 3;
const int * ps = &sloth; // a pointer to const int
int * const finger = &sloth; a const pointer to int
Note that the last declaration has repositioned the keyword const. This form of declaration constrains finger to point only to sloth. However, it allows you to use finger to alther the value of sloth. The middle declaration does not allow you to use ps to alter the value of sloth, but it permits you to have ps point to another location. In short, finger and *ps are both const, and *finger and ps are not const.
If you like, you can declare a const pointer to a const object:
double trouble = 2.0E30;
const double * const stick = &trouble;
Here stick can point only to trouble, and stick cannot be used to change the value of trouble. In short both stick and *stick are const.
Typically you use the pointer to const form to protect data when you pass pointers as function arguments. For example:
void show_array(const double ar[], int n);
Using const in this declaration means that show_array() cannot alter the values in any array that is passed to it. This technique works as long as there is just one level of indirection. Here for example, the array elements are fundamental type, but if they where pointers or pointers-to-pointers, you wouldn't use const.
Functions Using Array ranges
The STL approach uses the concept of "one past the end" to indicate an extent. That is, in the case of an array, the argument identifying the end of the array would be a pointer to the location just after the last element. For example, suppose you have this declaration:
double elbuod[20]
Then the two pointers elboud and elboud + 20 define the range. First, elboub, being the name of the array, points to the first element. The expression elboud + 19 points to the last element (that is, elboud[19]), so elboud + 20 points to one past the end of the array. Passing a range to a function tells it which elements to process.
Example:
for (pt = begin; pt != end; pt++)
total = total + *pt;
here begin is a pointer to the first element of an array
here end is a pointer one past the end from the array, easy because you can give the size of the array as end value pointer
int sum = sum_arr(cookies, cookies + ArSize);
so the end is cookies array address + ArSize, which is the array size, which is always one to much because arrays start counting at zero, in this case to 7, but the size is counted from 1 to 8 so 8 is one past the end.
Note by the way that rules for pointer subtraction imply that, in sum_arr(), the expression end - begin is an integer value equal to the number of elements in the range.
So 8 - 0 = 8, so there are 8 elements in the array!
double elbuod[20]
Then the two pointers elboud and elboud + 20 define the range. First, elboub, being the name of the array, points to the first element. The expression elboud + 19 points to the last element (that is, elboud[19]), so elboud + 20 points to one past the end of the array. Passing a range to a function tells it which elements to process.
Example:
for (pt = begin; pt != end; pt++)
total = total + *pt;
here begin is a pointer to the first element of an array
here end is a pointer one past the end from the array, easy because you can give the size of the array as end value pointer
int sum = sum_arr(cookies, cookies + ArSize);
so the end is cookies array address + ArSize, which is the array size, which is always one to much because arrays start counting at zero, in this case to 7, but the size is counted from 1 to 8 so 8 is one past the end.
Note by the way that rules for pointer subtraction imply that, in sum_arr(), the expression end - begin is an integer value equal to the number of elements in the range.
So 8 - 0 = 8, so there are 8 elements in the array!
Display an array with a function
Building a function to display the array is simple. You pass the name of the array and the number of filled elements to the function, which then uses a loop to display each element.
But there is another consideration--guaranteeing that the display function doesn't alter the original array.
Unless the purpose of a function is to alter data passed to it, you should safeguard it from doing so. That protection comes automaticaly with ordinary arguments because C++ passes them by value, and the function works with a copy. But functions that use an array work with the original.
To keep a function from accidently altering the contents of an array argument, you can use the keyword CONST when you declare the formal argument:
void show_array(const double ar[], int n);
The declaration states that the pointer ar points to constant data. This means that you can't use ar to change the data. That is, you can use a value such as ar[0], but you can't change that value. Thus, show_array() treats the array as read-only data.
If you try to modify const data, your compiler will create an error and a message describing what you tried to do.
This is the code for the show_array() function:
void show_array(const double ar[], int n)
{
using namespace std;
for (int i = 0; i < n; ++i)
{
cout << "Property #" << (i + 1) << ": $";
cout << ar[i] << endl;
}
}
But there is another consideration--guaranteeing that the display function doesn't alter the original array.
Unless the purpose of a function is to alter data passed to it, you should safeguard it from doing so. That protection comes automaticaly with ordinary arguments because C++ passes them by value, and the function works with a copy. But functions that use an array work with the original.
To keep a function from accidently altering the contents of an array argument, you can use the keyword CONST when you declare the formal argument:
void show_array(const double ar[], int n);
The declaration states that the pointer ar points to constant data. This means that you can't use ar to change the data. That is, you can use a value such as ar[0], but you can't change that value. Thus, show_array() treats the array as read-only data.
If you try to modify const data, your compiler will create an error and a message describing what you tried to do.
This is the code for the show_array() function:
void show_array(const double ar[], int n)
{
using namespace std;
for (int i = 0; i < n; ++i)
{
cout << "Property #" << (i + 1) << ": $";
cout << ar[i] << endl;
}
}
Functions and Arrays
The sample functions I talked about in some previous blogs are very simple, basic. They only use build in data types for arguments and return values.
But now let's talk about functions that uses arrays and structures as argument or return type.
Suppose you use an array to keep track of how many cookies each person has eaten at a family picnic. (each array index corresponds to a person, and the value of the element corresponds to the number of cookies that person has eaten.) Now you want the total. That's easy to find; you just loop to add all the array elements. But adding array elements is such a common task that it makes sense to design a function for the job.
Then you don't have to write a new loop everythime you have to sum an array.
int sum_arr(int arr[], int n) // arr = array name, n = size
This looks plausible. The brackets seem to indicate that arr is an array, and the fact that the brackets are empty seems to indicate that you can use the function with an array of any size.
BUT THINGS ARE NOT ALWAYS AS THEY SEEM!
arr is not really an array, it's a pointer!
The good news is that you can write the rest of the function just as if arr were an array.
here is the function:
// return the sum of an integer array
int sum_arr(int arr[], int n)
{
int total = 0;
for (int i = 0; i < total =" total" cookies ="="" sum =" sum_arr(cookies," arr =" array" n =" size" i =" 0;">> temp;
if (!cin) // bad input
{
cin.clear()
while (cin.get() != '\n')
continue;
cout << "Bad input; input process terminated.\n";
break;
}
else if (temp =< 0) // signal to terminate
break;
ar[i] = temp;
}
return i;
}
Note that this code includes a prompt to the user. If the user enters a non-negative value, the value is assigned to the array. Otherwise the loop terminates. If the user enters only valid values, the loop terminates after it reads limit values. The last thing the loop does is incrementing i, so after the loop terminate, i is one greater then the last array index, hence it's equal to the number of filled elements. The function returns that value.
But now let's talk about functions that uses arrays and structures as argument or return type.
Suppose you use an array to keep track of how many cookies each person has eaten at a family picnic. (each array index corresponds to a person, and the value of the element corresponds to the number of cookies that person has eaten.) Now you want the total. That's easy to find; you just loop to add all the array elements. But adding array elements is such a common task that it makes sense to design a function for the job.
Then you don't have to write a new loop everythime you have to sum an array.
int sum_arr(int arr[], int n) // arr = array name, n = size
This looks plausible. The brackets seem to indicate that arr is an array, and the fact that the brackets are empty seems to indicate that you can use the function with an array of any size.
BUT THINGS ARE NOT ALWAYS AS THEY SEEM!
arr is not really an array, it's a pointer!
The good news is that you can write the rest of the function just as if arr were an array.
here is the function:
// return the sum of an integer array
int sum_arr(int arr[], int n)
{
int total = 0;
for (int i = 0; i < total =" total" cookies ="="" sum =" sum_arr(cookies," arr =" array" n =" size" i =" 0;">> temp;
if (!cin) // bad input
{
cin.clear()
while (cin.get() != '\n')
continue;
cout << "Bad input; input process terminated.\n";
break;
}
else if (temp =< 0) // signal to terminate
break;
ar[i] = temp;
}
return i;
}
Note that this code includes a prompt to the user. If the user enters a non-negative value, the value is assigned to the array. Otherwise the loop terminates. If the user enters only valid values, the loop terminates after it reads limit values. The last thing the loop does is incrementing i, so after the loop terminate, i is one greater then the last array index, hence it's equal to the number of filled elements. The function returns that value.
Two kinds of local variables
long double probability(unsigned numbers, unsigned picks)
{
long double result = 1.0; // here come some local variables
long double n;
unsigned p;
for (n = numbers, p = picks; p > 0; n--, p--)
result = result * n / p ;
return result;
}
The probability() function illustrates two kinds of local variables you can have in a function. First there are the formal parameters (numbers and picks), which are declared in the function header before the opening brace. Then come the other local variables (result, n and p). They are declared in between the braces bounding the function definition.
The main difference between the formal parameters and the other local variables is that the formal parameters get their values from the function that calls probability(), whereas the other variables get values from within the function.
{
long double result = 1.0; // here come some local variables
long double n;
unsigned p;
for (n = numbers, p = picks; p > 0; n--, p--)
result = result * n / p ;
return result;
}
The probability() function illustrates two kinds of local variables you can have in a function. First there are the formal parameters (numbers and picks), which are declared in the function header before the opening brace. Then come the other local variables (result, n and p). They are declared in between the braces bounding the function definition.
The main difference between the formal parameters and the other local variables is that the formal parameters get their values from the function that calls probability(), whereas the other variables get values from within the function.
Something about cin >> ch and cin.get()
In a example in my book they used cin >> ch, instead of using cin.get(ch) or ch = cin.get().
The reason is that cin >> ch, skips all whitespace including '\n'.
cin.get(ch) will read all input characters, including spaces and newlines.
So it is often more easy to use cin >> ch then using cin.get(), however ofcourse you can program arround the cin.get() behaviour.
The reason is that cin >> ch, skips all whitespace including '\n'.
cin.get(ch) will read all input characters, including spaces and newlines.
So it is often more easy to use cin >> ch then using cin.get(), however ofcourse you can program arround the cin.get() behaviour.
Multiple Arguments to functions
A function can have more than one argument. In the function call, you separate the arguments with commas:
n_chars('R', 25);
This passes two arguments to the function n_chars().
Similarly, when you define the function, you use a comma-seperated list of parameter declarations in the function header:
void n_chars(char c, int n) // two arguments
This function header states that the function n_chars() takes one type char argument and one type int argument. The parameters c and n are assigned the values passed to the function.
If a function has two parameters of the same type, you have to give the type of each parameter seperately.
void fifi(float a, float b) // declare each variable separately
void fufu(float a, b) // NOT acceptable
As with other functions, you just add a semicolon to get a prototype
void n_chars(char c, int n); // prototype, style 1
void n_chars(char, int); // prototype style 2
However, providing variable names can make the prototype more understandable, particularly if two parameters are the same type. Then, the names can remind you which argument is which:
double melon_density(double weight, double volume);
n_chars('R', 25);
This passes two arguments to the function n_chars().
Similarly, when you define the function, you use a comma-seperated list of parameter declarations in the function header:
void n_chars(char c, int n) // two arguments
This function header states that the function n_chars() takes one type char argument and one type int argument. The parameters c and n are assigned the values passed to the function.
If a function has two parameters of the same type, you have to give the type of each parameter seperately.
void fifi(float a, float b) // declare each variable separately
void fufu(float a, b) // NOT acceptable
As with other functions, you just add a semicolon to get a prototype
void n_chars(char c, int n); // prototype, style 1
void n_chars(char, int); // prototype style 2
However, providing variable names can make the prototype more understandable, particularly if two parameters are the same type. Then, the names can remind you which argument is which:
double melon_density(double weight, double volume);
dinsdag 19 juni 2007
Function Arguments and Passing by Value
C++ normally passes arguments by value.
That means the numeric value of the argument is passed to the function, where it is assigned to a new variable.
double volume = cube(side);
Here side is a variable that, in the sample run, had the value 5.
The function header for cube() was this:
double cube(double x)
When this function is called, it creates a new type double variable called x and assigns the value 5 to it.
This insulates data in main() from actions that take place in cube() because cube() works with a copy of side rather than with the original data.
A variable that's used to receive passed values is called a formal argument or a formal parameter. The value passed to the function is called the actual argument or the actual parameter.
Variables, including parameters, declared within a function are private to the function. When a function is called, the computer allocates the memory needed for these variables. When the function terminates, the computer frees the memory that was used for those variables.
Such variables are called local variables because they are localized to the function.
It also means that if you declare a variable called x in main() and another variable called x in some other function, these are two distinct, unrelated variables.
Such variables are also termed automatic variables because they are allocated and deallocated automatically during program execution.
That means the numeric value of the argument is passed to the function, where it is assigned to a new variable.
double volume = cube(side);
Here side is a variable that, in the sample run, had the value 5.
The function header for cube() was this:
double cube(double x)
When this function is called, it creates a new type double variable called x and assigns the value 5 to it.
This insulates data in main() from actions that take place in cube() because cube() works with a copy of side rather than with the original data.
A variable that's used to receive passed values is called a formal argument or a formal parameter. The value passed to the function is called the actual argument or the actual parameter.
Variables, including parameters, declared within a function are private to the function. When a function is called, the computer allocates the memory needed for these variables. When the function terminates, the computer frees the memory that was used for those variables.
Such variables are called local variables because they are localized to the function.
It also means that if you declare a variable called x in main() and another variable called x in some other function, these are two distinct, unrelated variables.
Such variables are also termed automatic variables because they are allocated and deallocated automatically during program execution.
Functions
To create your own functions in C++, you need the following:
- Provide a function definition
- Provide a function prototype
- Call the function
If you're using a library function, the function has already been defined and compiled for you.
Also you can use the standard library header file to provide the prototype.
All that is left to do is call the function properly.
The associated standard header file cstring contains the function prototype for strlen() and several other string related functions. This advance work allows you to use the strlen() function in programs without further worries.
But when you create your own functions, you have to handle all three aspects--defining, prototyping, and calling---yourself.
Here is a short example:
void simple(); // function prototype, before main()
main()
{
using namespace std;
cout << "main() will call the simple() function:\n"; simple(); // function call return 0; } // function definition (after main()) void simple() { using namespace std; cout << "I'm but a simple function.\n"; } Defining a Function You can group functions into two categories: those that don't have return values and those that do. Functions without return values are termed type void functions and have the following general form: void functionName(parameterList) { statement(s) return; // optional } A function with a return value produces a value that it returns to the function that called it. Here is the general form: typeName functionName(parameterList) { statements return value; // value is type cast to type typeName } Functions with return values require that you use a return statement so that the value is returned to the calling function. The value itself, can be a constant, a variable, or a more general expression. The only requirement is that the expression reduce to a value that has, or is convertible to, the typeName type. C++ does place a restriction on what types you can use for a return value: The return value CAN NOT be an ARRAY. Everything else is possible. (Interestingly, even though a C++ function can't return an array directly, it can return an array that is part of a structure or object!) As a programmer, you don't need to know how a function returns a value, but knowing the method might clarify the concept for you. Typically, a function returns a value by copying the return value to a specified CPU register or memory location. Then the calling program examines that location. Both the returning function and the calling function have to agree on the type of data at that location. The function prototype tells the calling program what to expect, and the function definition tells the called program what to return. A function terminates after excecuting a return statement. If a function has more than one return statement--for example, as alternatives to different if else selections--the function terminates after it excecutes the first return statement it reaches. For example, in the folowing example, the else isn't needed, but it does help the casual reader understand the intent: int bigger(int a, int b) { if (a > b)
return a; // if a > b, function terminates here
else
return b; // otherwise, function terminates here
}
Functions with a return value, return a value to the calling program, which can then assign that value to a variable, display the value, or otherwise use it.
Here's a simple example that returns the cube of a type double value:
double cube(double x) // x times x times x
{
return x * x * x; // a type double value
}
For example, the function call cube(1.2) returns the value 1.728. Note that this return statement uses an expression. The function computes the value of the expression(1.728, in this case) and returns the value.
Why Prototypes?
A prototype describes the function interface to the compiler. That is, it tells the compiler what type of return value, if any, the function has, and it tells the compiler the number and type of function arguments. Consider, for example, how a prototype affects this function call:
double volume = cube(side);
First, the prototype tells the compiler that cube() should have one type double argument. If the program fails to provide the argument, prototyping allows the compiler to catch the error. Second, when the cube() function finishes its calculation, it places the return value at some specified location--perhaps in a CPU register, perhaps in memory. Then the calling function main() in this case, retrieves the value from that location. Because the prototype states that cube() is type double, the compiler knows how many bytes to retrieve and how to interpret them. Without that information, the compiler could only guess, and that is something compilers won't do.
Still, you migth wonder, why does the compiler need a prototype? Can't it just look further in the file and see how functions are defined? One problem with that approach is that it is not very efficient. The compiler would have to put compiling main() on hold while searching the rest of the file. An even more serious problem is the fact that the function might not even be in the file. C++ allows you to spread a program over several files, which you can compile independently and then combine later. In such a case, the compiler might not have access to the function code when it's compiling main(). The same is true if the function is part of a library. The only way to avoid using a function prototype is to place the function definition before its first use. That is not always possible. Also, the C++ programming style is to put main() first because it generally provides the structure for the whole program.
Prototype Syntax
A function prototype is a statement, so it MUST have a TERMINATING SEMICOLON. The simplest way to get a prototype is to copy the function header from the function definition and add a semicolon.
double cube(double x); // add ; to header to get prototype
However, the function prototype does NOT require that you provide names for the variables; a list of types is enough.
void cheers(int); // okay to drop variable names in prototype
In general, you can either include or exclude variable names in the argument lists for prototypes. The variable names in the prototype just act as placeholders, so if you do use names, they don't have to match the names in the function definition.
Classic C made prototyping optional, whereas C++ makes prototyping mandatory.
What Prototypes Do for You
They greatly reduce the changes of program errors.
- The compiler correctly handles the return value.
- The compiler checks that you use the correct number of function arguments
- The compiler checks that you use the correct type of arguments. If you don't, it converts the arguments to the correct type, if possible.
C++ automatically converts the value you pass to the type specified in the prototype, provided that both are arithmetic types.
cheers(cube(2));
This code is using two type mismatches in one statement.
First, the program passes the int value of 2 to cube(), which expects a double. The compiler, nothing that the cube() prototype specifies a type double argument, converts 2 to 2.0, a type double value. Then, cube() returns a type double value (8.0) to be used as an argument to cheers(). Again the compiler checks the prototypes and notes that cheers() requires an int. It converts the return value to integer 8. In general, prototyping produces automatic type casts to the expected types.
Prototyping takes place during compile time and is termed static type checking. Static type checking, as you've seen, catches many errors that are much more difficult to catch during runtime.
- Provide a function definition
- Provide a function prototype
- Call the function
If you're using a library function, the function has already been defined and compiled for you.
Also you can use the standard library header file to provide the prototype.
All that is left to do is call the function properly.
The associated standard header file cstring contains the function prototype for strlen() and several other string related functions. This advance work allows you to use the strlen() function in programs without further worries.
But when you create your own functions, you have to handle all three aspects--defining, prototyping, and calling---yourself.
Here is a short example:
void simple(); // function prototype, before main()
main()
{
using namespace std;
cout << "main() will call the simple() function:\n"; simple(); // function call return 0; } // function definition (after main()) void simple() { using namespace std; cout << "I'm but a simple function.\n"; } Defining a Function You can group functions into two categories: those that don't have return values and those that do. Functions without return values are termed type void functions and have the following general form: void functionName(parameterList) { statement(s) return; // optional } A function with a return value produces a value that it returns to the function that called it. Here is the general form: typeName functionName(parameterList) { statements return value; // value is type cast to type typeName } Functions with return values require that you use a return statement so that the value is returned to the calling function. The value itself, can be a constant, a variable, or a more general expression. The only requirement is that the expression reduce to a value that has, or is convertible to, the typeName type. C++ does place a restriction on what types you can use for a return value: The return value CAN NOT be an ARRAY. Everything else is possible. (Interestingly, even though a C++ function can't return an array directly, it can return an array that is part of a structure or object!) As a programmer, you don't need to know how a function returns a value, but knowing the method might clarify the concept for you. Typically, a function returns a value by copying the return value to a specified CPU register or memory location. Then the calling program examines that location. Both the returning function and the calling function have to agree on the type of data at that location. The function prototype tells the calling program what to expect, and the function definition tells the called program what to return. A function terminates after excecuting a return statement. If a function has more than one return statement--for example, as alternatives to different if else selections--the function terminates after it excecutes the first return statement it reaches. For example, in the folowing example, the else isn't needed, but it does help the casual reader understand the intent: int bigger(int a, int b) { if (a > b)
return a; // if a > b, function terminates here
else
return b; // otherwise, function terminates here
}
Functions with a return value, return a value to the calling program, which can then assign that value to a variable, display the value, or otherwise use it.
Here's a simple example that returns the cube of a type double value:
double cube(double x) // x times x times x
{
return x * x * x; // a type double value
}
For example, the function call cube(1.2) returns the value 1.728. Note that this return statement uses an expression. The function computes the value of the expression(1.728, in this case) and returns the value.
Why Prototypes?
A prototype describes the function interface to the compiler. That is, it tells the compiler what type of return value, if any, the function has, and it tells the compiler the number and type of function arguments. Consider, for example, how a prototype affects this function call:
double volume = cube(side);
First, the prototype tells the compiler that cube() should have one type double argument. If the program fails to provide the argument, prototyping allows the compiler to catch the error. Second, when the cube() function finishes its calculation, it places the return value at some specified location--perhaps in a CPU register, perhaps in memory. Then the calling function main() in this case, retrieves the value from that location. Because the prototype states that cube() is type double, the compiler knows how many bytes to retrieve and how to interpret them. Without that information, the compiler could only guess, and that is something compilers won't do.
Still, you migth wonder, why does the compiler need a prototype? Can't it just look further in the file and see how functions are defined? One problem with that approach is that it is not very efficient. The compiler would have to put compiling main() on hold while searching the rest of the file. An even more serious problem is the fact that the function might not even be in the file. C++ allows you to spread a program over several files, which you can compile independently and then combine later. In such a case, the compiler might not have access to the function code when it's compiling main(). The same is true if the function is part of a library. The only way to avoid using a function prototype is to place the function definition before its first use. That is not always possible. Also, the C++ programming style is to put main() first because it generally provides the structure for the whole program.
Prototype Syntax
A function prototype is a statement, so it MUST have a TERMINATING SEMICOLON. The simplest way to get a prototype is to copy the function header from the function definition and add a semicolon.
double cube(double x); // add ; to header to get prototype
However, the function prototype does NOT require that you provide names for the variables; a list of types is enough.
void cheers(int); // okay to drop variable names in prototype
In general, you can either include or exclude variable names in the argument lists for prototypes. The variable names in the prototype just act as placeholders, so if you do use names, they don't have to match the names in the function definition.
Classic C made prototyping optional, whereas C++ makes prototyping mandatory.
What Prototypes Do for You
They greatly reduce the changes of program errors.
- The compiler correctly handles the return value.
- The compiler checks that you use the correct number of function arguments
- The compiler checks that you use the correct type of arguments. If you don't, it converts the arguments to the correct type, if possible.
C++ automatically converts the value you pass to the type specified in the prototype, provided that both are arithmetic types.
cheers(cube(2));
This code is using two type mismatches in one statement.
First, the program passes the int value of 2 to cube(), which expects a double. The compiler, nothing that the cube() prototype specifies a type double argument, converts 2 to 2.0, a type double value. Then, cube() returns a type double value (8.0) to be used as an argument to cheers(). Again the compiler checks the prototypes and notes that cheers() requires an int. It converts the return value to integer 8. In general, prototyping produces automatic type casts to the expected types.
Prototyping takes place during compile time and is termed static type checking. Static type checking, as you've seen, catches many errors that are much more difficult to catch during runtime.
Let cin flush the buffer
std::cin.ignore(std::numeric_limits::max(), '\n');
Will remove all unwanted input from the input buffer.
Will remove all unwanted input from the input buffer.
maandag 18 juni 2007
Simple File Input, reading from a text file
Text file input is based on console input, which has many elements. So let's begin with a summary of those elements.
- You must include the iostream header file
- The iostream header file defines an istream class for handling input
- The iostream header file declares an istream variable, or object, called cin
- You must account for the std namespace; for example you can use the using directive or the std:: prefix for elements such as cin
- You can use cin with the >> operator to read a variety of data types
- You can use cin with the get() method to read individual characters and with getline() method to read a line of characters at a time.
- You can use cin with methods such as eof() and fail() to monitor the success of an input attempt
- The object cin itself, when used as a test condition, is converted to the Boolean value true if the last read attempt succeeded and to false otherwise.
File input parallels this very closely:
- You must include the fstream header
- The fstream header file defines an ifstream class for handling input
- You need to declare one or more ifstream variables, or objects, which you can name as you please, as long as you respect the usual naming conventions
- You must account for the std namespace; for example, you can use the using directive or the std:: prefix for elements such as ifstream
- You need to associate a specific ifstream object with a specific file; one way to do so is to use the open() method
- When you're finished with a file, you should use the close() method to close the file
- You can use the ifstream object with the >> operator to read a variety of data types
- You can use an ifstream object with the get() method to read individual characters and with the getline() method to read a line of characters at a time
- You can use an ifstream object with methods such as eof() and fail() to monitor the success of an input attempt.
- An ifstream object itself, when used as a test condition, is converted to the Boolean value true if the last read attempt succeeded and to false otherwise.
Note that although the iostream header file provides a predefined istream object called cin, you have to declare your own ifstream object, choosing a name for it and associating it with a file. Here is how you declare such objects:
ifstream inFile; // inFile an ifstream object
ifstream fin; // fin an ifstream object
Here's how you can associate them with particular files:
inFile.open("bowling.txt"); // inFile used to read bowling.txt file
char filename[50];
cin >> filename; // user specifies a file name
fin.open(filename); // fin used to read specified file
Note that the open() method requires a C-Style string as its argument. This can be a literal string or a string stored in an array.
Here's how you can use these objects:
double wt;
inFile >> wt; // read a number from bowling.txt
char line[81];
fin.getline(line, 81); // read a line of text
The important point is that after you've declared an ifstream object and associated it with a file, you can use it exactly as you would use cin. All the methods and operations available to cin are also available to ifstream objects, such as inFile and fin in the preceding examples.
What happens if you attempt to open a non-existing file for input? This error causes subsequent attempts to use the ifstream object for input to fail. The prefered method to check if a file has opened successfully is to use the is_open() method. You can use code like this:
inFile.open("bowling.txt");
if (!inFile.is_open())
{
exit(EXIT_FAILURE);
}
The is_open() method returns true if the file was opened successfully, so the expression !inFile.is_open() is true if the attempt fails. The exit() function is prototyped in the CSTDLIB header file, which also defines EXIT_FAILURE as an argument value used to communicate with the operating system. The exit() function terminates the program.
The is_open() method is relatively new to C++. If your compiler doesn't support it, you can use the older good() method instead.
To close a file, use inFile.close();
- You must include the iostream header file
- The iostream header file defines an istream class for handling input
- The iostream header file declares an istream variable, or object, called cin
- You must account for the std namespace; for example you can use the using directive or the std:: prefix for elements such as cin
- You can use cin with the >> operator to read a variety of data types
- You can use cin with the get() method to read individual characters and with getline() method to read a line of characters at a time.
- You can use cin with methods such as eof() and fail() to monitor the success of an input attempt
- The object cin itself, when used as a test condition, is converted to the Boolean value true if the last read attempt succeeded and to false otherwise.
File input parallels this very closely:
- You must include the fstream header
- The fstream header file defines an ifstream class for handling input
- You need to declare one or more ifstream variables, or objects, which you can name as you please, as long as you respect the usual naming conventions
- You must account for the std namespace; for example, you can use the using directive or the std:: prefix for elements such as ifstream
- You need to associate a specific ifstream object with a specific file; one way to do so is to use the open() method
- When you're finished with a file, you should use the close() method to close the file
- You can use the ifstream object with the >> operator to read a variety of data types
- You can use an ifstream object with the get() method to read individual characters and with the getline() method to read a line of characters at a time
- You can use an ifstream object with methods such as eof() and fail() to monitor the success of an input attempt.
- An ifstream object itself, when used as a test condition, is converted to the Boolean value true if the last read attempt succeeded and to false otherwise.
Note that although the iostream header file provides a predefined istream object called cin, you have to declare your own ifstream object, choosing a name for it and associating it with a file. Here is how you declare such objects:
ifstream inFile; // inFile an ifstream object
ifstream fin; // fin an ifstream object
Here's how you can associate them with particular files:
inFile.open("bowling.txt"); // inFile used to read bowling.txt file
char filename[50];
cin >> filename; // user specifies a file name
fin.open(filename); // fin used to read specified file
Note that the open() method requires a C-Style string as its argument. This can be a literal string or a string stored in an array.
Here's how you can use these objects:
double wt;
inFile >> wt; // read a number from bowling.txt
char line[81];
fin.getline(line, 81); // read a line of text
The important point is that after you've declared an ifstream object and associated it with a file, you can use it exactly as you would use cin. All the methods and operations available to cin are also available to ifstream objects, such as inFile and fin in the preceding examples.
What happens if you attempt to open a non-existing file for input? This error causes subsequent attempts to use the ifstream object for input to fail. The prefered method to check if a file has opened successfully is to use the is_open() method. You can use code like this:
inFile.open("bowling.txt");
if (!inFile.is_open())
{
exit(EXIT_FAILURE);
}
The is_open() method returns true if the file was opened successfully, so the expression !inFile.is_open() is true if the attempt fails. The exit() function is prototyped in the CSTDLIB header file, which also defines EXIT_FAILURE as an argument value used to communicate with the operating system. The exit() function terminates the program.
The is_open() method is relatively new to C++. If your compiler doesn't support it, you can use the older good() method instead.
To close a file, use inFile.close();
Simple File Input/Output part II
Note that although the iostream header file provides a predifined ostream object called cout, you have to declare your own ofstream object, choosing a name for it and associating it with a file. Here's how you declare such objects:
ofstream outFile; // outFile an ofstream object
ofstream fout; // fout an ofstream object
Here's how you can associate the objects with particular files:
outFile.open("fish.txt"); // outFile used to write to the fish.txt file
char filename[50];
cin >> filename; // user specifies name
fout.open(filename); // fout used to read specified file
Note that the open() method requires a C-style string as its argument. This can be a literal string or a string stored in an array.
Here's how you can use these objects:
double wt = 125.8;
outfile << wt;
char line[81] = "Objects are closer than they appear.";
fout << line << endl; // write a line of text
The important point is after you declared an ofstream object and associated it with a file, you use it exactly as you would use cout. All the operations and methods available to cout, such as <<, endl, and setf(), are also available to ofstream objects, such as outFile and fout in the preceding examples.
In short, these are the main steps for using file output:
1. Include the fstream header
2. Create an ofstream object
3. Associate the ofstream object with a file.
4. Use the ofstream object in the same manner you would use cout.
NOTE: If you use open() and the file you open already exists, the size of the file is made zero, the contents are then replaced with new output.
One of the last chapters will show me how to override this default behaviour.
So then I will write about it.
ofstream outFile; // outFile an ofstream object
ofstream fout; // fout an ofstream object
Here's how you can associate the objects with particular files:
outFile.open("fish.txt"); // outFile used to write to the fish.txt file
char filename[50];
cin >> filename; // user specifies name
fout.open(filename); // fout used to read specified file
Note that the open() method requires a C-style string as its argument. This can be a literal string or a string stored in an array.
Here's how you can use these objects:
double wt = 125.8;
outfile << wt;
char line[81] = "Objects are closer than they appear.";
fout << line << endl; // write a line of text
The important point is after you declared an ofstream object and associated it with a file, you use it exactly as you would use cout. All the operations and methods available to cout, such as <<, endl, and setf(), are also available to ofstream objects, such as outFile and fout in the preceding examples.
In short, these are the main steps for using file output:
1. Include the fstream header
2. Create an ofstream object
3. Associate the ofstream object with a file.
4. Use the ofstream object in the same manner you would use cout.
NOTE: If you use open() and the file you open already exists, the size of the file is made zero, the contents are then replaced with new output.
One of the last chapters will show me how to override this default behaviour.
So then I will write about it.
Simple File Input/Output part I
Sometimes keyboard input is not the best choice. For example, suppose you have written a program to analyze stocks, and you've downloaded a file of 1,000 stock prices. It would be far more convenient to have the program read the file directly than to hand enter all the values.
Similarly, it can be convenient to have a program write output to a file so that you have a permanent record of the results.
Fortunately, C++ makes it simple to transfer the skills you've acquired for keyboard input and output (collectively termed console I/O) to file input and output (file I/O). Later I will place more details about file I/O, but the book I read covers that at the end of the book.
But we'll look at simple text file I/O now.
Text I/O and Text Files
Let's reexamine the concept of text I/O. When you use cin for input, the program views input as a series of bytes, with each byte being interpreted as a character code. No matter what the destination destination data type, the input begins as character data--that is, text data. The cin object then has the responsibility of translating text to other types. To see how this works, let's examine how different code handles the same line of input/
Suppose you have the following sample line of input:
38.5 19.2
Let's see how this line of input is handled by cin when used with different data types. First, let's try type char:
char ch;
cin >> ch;
The first character in the input line is assigned to ch. In this case, the first character is the digit 3, and the character code (in binary) for this digit is stored in ch. The input and the destination are both characters, so no translation is needed. (Note that it's not the numeric value 3 that is stored; rather it is the character code for digit 3.) After the input statement, the digit character 8 is the next character in the input queue and will be the next character examined by the next input operation.
Next, let's try the int type:
int n;
cin >> n;
In this case, cin reads up to the first non-digit character. That is, it reads the 3 digit and the 8 digit, leaving the period as the next character in the input queue. Then cin computes that these two characters correspond to the numeric value 38, and the binary code for 38 is copied to n.
Next, let's try the double type:
double x;
cin >> x;
In this case, cin reads up to the first character that's not part of a floating point number. That is, it reads the 3 digit, the 8 digit, the period character, and the 5 digit, leaving the space as the next character in the input queue. Then cin computes that these four characters correspond to the numeric value 38.5, and the binary code (floating point format) for 38.5 is copied to x.
Next, let's try the char array type:
char word[50];
cin >> word;
In this case, cin reads up to the whitespace character. That is, it reads the 3 digit, the 8 digit, the period character, and the 5 digit, leaving the space as next character in the input queue. Then cin stores the character code for these four characters in the array word and adds a terminating null character. No translation is needed.
Finally, let's try an input variant for the char array type:
char word[50];
cin.getline(word, 50);
In this case, cin reads up to the newline character. All the characters through the final 2 digit are stored in the array word, and a null character is added. The newline character is discarded, and the next character in the input queue will be the first character on the next line. No translation is needed.
On output, the opposite translations take place. That is, integers are converted to sequences of digit characters, and floating point numbers are converted to sequences of digits and other characters (for example, 284.53 or -1.587E+06).
Character data requires no translation.
The main point to this is that all the input starts out as text. Therefore, the file equivalent to console input is a text file--that is, a file in which each byte stores a character code. Not all files are text files. For example, databases and spreadsheets store numeric data in numeric forms--that is, in binary integer or binary floating-point form. Also, word processing files may contain text information, but they also contain non-text data to describe formatting, fonts, printers, and the like.
The file I/O discussed now parallels console I/O and thus should be used with text files. To create a text file for input, you use a text editor, such as EDIT for DOS, Notepad for Windows, or vi or emacs for Unix/Linux.
The code editors that are part of IDE's also produce text files; indeed, the source code files are examples of text files. Similarly, you can use text editors to look at files created with text output.
File output is very much like console output:
Console output:
- You must include the iostream header file
- The iostream header file defines an ostream class for handling output
- The iostream header file declares an ostream variable, or object, cout
- You must account for the std namespace; for example, you can use the using
directive or the std:: prefix for elements such as cout and endl;
- You can use cout with the << operator to write a variety of data types.
File output parallels this very closely:
- You must include the fstream header file
- The fstream header file defines an ofstream class for handling output
- You need to declare one or more ofstream variables, or objects, which you
can name as you please, as long as you respect the usual naming conventions.
- You must account for the std namespace; for example you can use the using directive or the std:: prefix for elements such as ofstream.
- You need to associate a specific ofstream object with a specific file; one way to do so id to use the open() method.
- When you're finished with a file, you should use the close() method to close the file.
- You can use an ofstream object with the << operator to output a variety of data types.
See the subject Simple File Input/Output part II
Similarly, it can be convenient to have a program write output to a file so that you have a permanent record of the results.
Fortunately, C++ makes it simple to transfer the skills you've acquired for keyboard input and output (collectively termed console I/O) to file input and output (file I/O). Later I will place more details about file I/O, but the book I read covers that at the end of the book.
But we'll look at simple text file I/O now.
Text I/O and Text Files
Let's reexamine the concept of text I/O. When you use cin for input, the program views input as a series of bytes, with each byte being interpreted as a character code. No matter what the destination destination data type, the input begins as character data--that is, text data. The cin object then has the responsibility of translating text to other types. To see how this works, let's examine how different code handles the same line of input/
Suppose you have the following sample line of input:
38.5 19.2
Let's see how this line of input is handled by cin when used with different data types. First, let's try type char:
char ch;
cin >> ch;
The first character in the input line is assigned to ch. In this case, the first character is the digit 3, and the character code (in binary) for this digit is stored in ch. The input and the destination are both characters, so no translation is needed. (Note that it's not the numeric value 3 that is stored; rather it is the character code for digit 3.) After the input statement, the digit character 8 is the next character in the input queue and will be the next character examined by the next input operation.
Next, let's try the int type:
int n;
cin >> n;
In this case, cin reads up to the first non-digit character. That is, it reads the 3 digit and the 8 digit, leaving the period as the next character in the input queue. Then cin computes that these two characters correspond to the numeric value 38, and the binary code for 38 is copied to n.
Next, let's try the double type:
double x;
cin >> x;
In this case, cin reads up to the first character that's not part of a floating point number. That is, it reads the 3 digit, the 8 digit, the period character, and the 5 digit, leaving the space as the next character in the input queue. Then cin computes that these four characters correspond to the numeric value 38.5, and the binary code (floating point format) for 38.5 is copied to x.
Next, let's try the char array type:
char word[50];
cin >> word;
In this case, cin reads up to the whitespace character. That is, it reads the 3 digit, the 8 digit, the period character, and the 5 digit, leaving the space as next character in the input queue. Then cin stores the character code for these four characters in the array word and adds a terminating null character. No translation is needed.
Finally, let's try an input variant for the char array type:
char word[50];
cin.getline(word, 50);
In this case, cin reads up to the newline character. All the characters through the final 2 digit are stored in the array word, and a null character is added. The newline character is discarded, and the next character in the input queue will be the first character on the next line. No translation is needed.
On output, the opposite translations take place. That is, integers are converted to sequences of digit characters, and floating point numbers are converted to sequences of digits and other characters (for example, 284.53 or -1.587E+06).
Character data requires no translation.
The main point to this is that all the input starts out as text. Therefore, the file equivalent to console input is a text file--that is, a file in which each byte stores a character code. Not all files are text files. For example, databases and spreadsheets store numeric data in numeric forms--that is, in binary integer or binary floating-point form. Also, word processing files may contain text information, but they also contain non-text data to describe formatting, fonts, printers, and the like.
The file I/O discussed now parallels console I/O and thus should be used with text files. To create a text file for input, you use a text editor, such as EDIT for DOS, Notepad for Windows, or vi or emacs for Unix/Linux.
The code editors that are part of IDE's also produce text files; indeed, the source code files are examples of text files. Similarly, you can use text editors to look at files created with text output.
File output is very much like console output:
Console output:
- You must include the iostream header file
- The iostream header file defines an ostream class for handling output
- The iostream header file declares an ostream variable, or object, cout
- You must account for the std namespace; for example, you can use the using
directive or the std:: prefix for elements such as cout and endl;
- You can use cout with the << operator to write a variety of data types.
File output parallels this very closely:
- You must include the fstream header file
- The fstream header file defines an ofstream class for handling output
- You need to declare one or more ofstream variables, or objects, which you
can name as you please, as long as you respect the usual naming conventions.
- You must account for the std namespace; for example you can use the using directive or the std:: prefix for elements such as ofstream.
- You need to associate a specific ofstream object with a specific file; one way to do so id to use the open() method.
- When you're finished with a file, you should use the close() method to close the file.
- You can use an ofstream object with the << operator to output a variety of data types.
See the subject Simple File Input/Output part II
Abonneren op:
Posts (Atom)