CSI 201 - Introduction to double interest_rate = .059; Types such - - PowerPoint PPT Presentation

csi 201 introduction to
SMART_READER_LITE
LIVE PREVIEW

CSI 201 - Introduction to double interest_rate = .059; Types such - - PowerPoint PPT Presentation

Introduction Up to now, we've known a variable to be a named reference to a place in memory that stores one type of data value. CSI 201 - Introduction to double interest_rate = .059; Types such as double , char , bool , int , etc. are


slide-1
SLIDE 1

CSI 201 - Introduction to Computer Science

Chapter 5 I/O Streams as an Introduction to Objects and Classes Brian R. King Instructor

2/26/2006 CSI 201 -- Chapter 05 2

Introduction

  • Up to now, we've known a variable to be a named reference to a

place in memory that stores one type of data value.

  • double interest_rate = .059;
  • Types such as double, char, bool, int, etc. are simple data types.

They are types built into the C++ language.

  • An object is a special kind of variable.
  • An object has:
  • data (sometimes referred to attributes, members, or member

fields, or fields)

  • member functions – special functions that are designed to work with

the data contained in the object.

  • Types for objects are complex data types, called classes. They are

made available through include directives and other means we'll discover in Chapter 6.

  • Chapter 6 will go into objects and classes in much more detail.
  • The goal of this chapter is to simply introduce you to the

concepts of objects and classes using the I/O Stream library.

2/26/2006 CSI 201 -- Chapter 05 3

Streams - Review

A stream is a flow of data to and from your program. C++ represents streams in your program as objects. Input is delivered to your program via an input stream object

The object is connected to the resource you want to read from.

  • cin is an input stream object connected to the keyboard.

Type (or class) – istream We say that cin is an instance of the class istream.

Output is sent to an output device via an output stream object

The object is connected to the resource you want to send data to.

  • cout is an output stream object connected to the screen.

Type (or class) – ostream We say that cout is an instance of the class ostream. 2/26/2006 CSI 201 -- Chapter 05 4

File I/O

Why use files?

Store data permanently Repeated input data

  • No need to repeatedly type your data in

Allows for large data set processing

How do we use files in our C++ programs?

C++ programs read and write data residing in files through file

stream objects.

File stream objects behave much like cin and cout. It will be our job to connect the file stream object to an actual file

managed by the OS's file system.

Terminology:

When a program takes data from a file, we say the program is

reading from the file.

When a program sends data to a file, we say the program is

writing to the file.

slide-2
SLIDE 2

2/26/2006 CSI 201 -- Chapter 05 5

Declaring our own stream variables

  • Recall, variables of simple data types (e.g. double, short, char,

int, etc.) must be declared before they can be used, and initialized before it contains valid data.

  • An object…
  • Must also be declared (sometimes called instantiated in OOP)
  • Must also be initialized before it contains valid data
  • For file stream objects, initialization means connecting the object to

an actual file residing in the file system.

  • Types whose variables are objects are called classes.
  • ifstream - The type for an input-file stream object.
  • fstream - The type for an output-file stream object.
  • These types are defined for you by using the include directive:

#include <fstream>

  • They are defined in the std namespace:

using namespace std;

  • Example declarations:
  • ifstream in_file;
  • fstream out_file;

2/26/2006 CSI 201 -- Chapter 05 6

How do we use a file stream object?

Objects have many actions and services available

that allow us to do things with the objects.

For file stream objects, some possible actions:

Opening a file to attach to the object? Testing for a failure incase the file couldn't be opened? Closing the file when we’re done with the file? Changing the format of data being sent to the file stream?

How are these actions and services invoked on the

  • bject?

Member function calls.

2/26/2006 CSI 201 -- Chapter 05 7

Member Function Call Syntax

  • bject.member_func(arg1, … ,argn);

The primary difference between a regular

function call and a member function call is the use of the "dot operator".

The left of a dot operator contains the name of an

  • bject.

The right of a dot operator contains the function

call that will accomplish the desired service provided by the object.

The right of the dot operator looks like a standard

function call as seen in Chapter 3-4.

2/26/2006 CSI 201 -- Chapter 05 8

Connecting a file to the stream:

After declaring a file stream object, it still needs to

be connected to a file.

  • pen - Our first example of a member function:

It takes one argument – a string containing the name of the

file to be opened.

ifstream in_file;

in_file.open("input.dat");

  • Interpret this as sending a request to object in_file to open

the file input.dat and attach it to it's input stream.

  • fstream out_file;
  • ut_file.open("output.dat");
slide-3
SLIDE 3

2/26/2006 CSI 201 -- Chapter 05 9

After the file has opened…

ifstream in_file;

  • fstream out_file;

in_file.open("input.dat");

  • ut_file.open("output.dat");

Now, in_file can be used to read data from the

file input.dat just like cin is used to read data from the keyboard.

  • ut_file can be used to write data to the file
  • utput.dat just like cout is used to write to the

screen.

2/26/2006 CSI 201 -- Chapter 05 10

Closing the file when completed

After you are finished using the file, you should

always close the file.

This releases the resource back to the operating system.

Use the member function close on the file stream

  • bject.

in_file.close();

  • ut_file.close();

What are reasons why we should close a file after

  • ur program is finished with the file?

2/26/2006 CSI 201 -- Chapter 05 11

ex1.cpp

#include <iostream> #include <fstream> using namespace std; int main() { ifstream in_file;

  • fstream out_file;

in_file.open("input.dat");

  • ut_file.open("output.dat");

double d1, d2, d3; in_file >> d1 >> d2 >> d3;

  • ut_file << "Average: " << (d1 + d2 + d3) / 3.0 << endl;

in_file.close();

  • ut_file.close();

cout << "Program completed." << endl; return 0; }

2/26/2006 CSI 201 -- Chapter 05 12

Input file open details

in_file.open("input.dat");

The postconditions of this function call depend on whether the file

input.dat can be successfully opened.

If so, it will be opened, ready for reading. If not, an internal success/fail flag maintained in the

in_file object will be set to true.

fail() member function - Test the state of the failure flag, thus

allowing us to test whether the open function succeeded.

in_file.fail() returns a type of bool.

true - the open failed false - the open succeeded.

Reasons for input files not opening successfully:

slide-4
SLIDE 4

2/26/2006 CSI 201 -- Chapter 05 13

Output file open details

  • ut_file.open("output.dat");

Creates the file, assuming a valid filename was given as an

argument to the function.

fail() member function – Test the success of the open

function call.

  • ut_file.fail() behaves the same way as we saw on input

stream objects.

NOTE - If the file already existed on the file system, then the

  • pen member function call above will cause the file to be
  • verwritten!
  • (There is a work around for this, next slide…)

Reasons for output files not opening successfully:

2/26/2006 CSI 201 -- Chapter 05 14

Append to a file (output stream only)

The open member function will overwrite the

file if the file already exists.

If you want to append data to a file so that

the data you write goes after any existing contents of the file, open the file using a second argument ios::app in the open function call:

  • ut_file.open("output.dat", ios::app);

2/26/2006 CSI 201 -- Chapter 05 15

If the file fails to open…

  • When a stream open function fails, sometimes it's best to stop

execution of the program.

  • The C++ standard library provides such a function:

exit(retValue);

  • It is NOT a member function of any object.
  • retValue represents any integer value that will be passed back to

the operating system.

  • Behaves similarly to the return statement in your main function.
  • Programmers have standardized on using an exit value of 0 to mean

a successful exit, and a non-zero (usually 1) to mean an error

  • ccurred in your program.
  • In order to use the exit function, you must have the following

directives: #include <cstdlib> using namespace std;

2/26/2006 CSI 201 -- Chapter 05 16

ex2.cpp – Using fail and exit

#include <iostream> #include <fstream> #include <cstdlib> using namespace std; int main() { ifstream in_file;

  • fstream out_file;

in_file.open("input.dat"); if (in_file.fail()) { cout << "Input file open failed!\n"; exit(1); }

  • ut_file.open("output.dat");

if (out_file.fail()) { cout << "Output file open failed!\n"; exit(1); }

slide-5
SLIDE 5

2/26/2006 CSI 201 -- Chapter 05 17

ex2.cpp continued…

double d1, d2, d3; in_file >> d1 >> d2 >> d3;

  • ut_file << "Average: " << (d1 + d2 + d3) / 3.0 << endl;

in_file.close();

  • ut_file.close();

cout << "Program completed." << endl; return 0; }

2/26/2006 CSI 201 -- Chapter 05 18

Filenames as variables

So far, we've been hardcoding literal strings into our program to

use with the open member function.

Suppose we want to ask the user for a filename to use. We need

a way to store strings.

Brief introduction to C-strings and arrays to be given in class. Example:

char filename[20]; Declares a variable called filename to store:

19 characters for the file name + the null-terminator character = 20 characters.

2/26/2006 CSI 201 -- Chapter 05 19

ex3.cpp

#include <iostream> #include <fstream> #include <cstdlib> using namespace std; int main() { ifstream in_file;

  • fstream out_file;

char filename[20]; cout << "Please enter the name of your input file: "; cin >> filename; in_file.open(filename); if (in_file.fail()) { cout << "Input file \"" << filename << "\" failed to open!\n"; cout << "Program terminated.\n"; exit(1); }

2/26/2006 CSI 201 -- Chapter 05 20

ex3.cpp continued…

cout << "Now enter the name of your output file: "; cin >> filename;

  • ut_file.open(filename);

if (out_file.fail()) { cout << "Output file \"" << filename << "\" failed to open!\n"; cout << "Program terminated.\n"; exit(1); } double d1, d2, d3; in_file >> d1 >> d2 >> d3;

  • ut_file << "Average: " << (d1 + d2 + d3) / 3.0 << endl;

in_file.close();

  • ut_file.close();

cout << "Program completed." << endl; return 0; }

slide-6
SLIDE 6

2/26/2006 CSI 201 -- Chapter 05 21

Formatting output (and ex4.cpp)

Recall that we used the setf and precision

member functions with cout cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2);

These are member functions of the ostream class.

They alter the behavior of certain types sent to the

  • utput stream.

All output streams objects have access to the same

formatting functions, including file output streams:

  • ut_file.setf(ios::fixed);
  • ut_file.setf(ios::showpoint);
  • ut_file.precision(2);

See ex4.cpp

2/26/2006 CSI 201 -- Chapter 05 22

More on precision…

precision is also a member function of the ostream class.

  • ut_stream.precision(2);
  • Restricts the output of floating point numbers to 2 significant digits

after the decimal point.

These ostream member functions affect output of all

numbers only on the object that it was called from!

double d = 23.4725;

  • fstream out_file;
  • ut_file.open("output.txt");
  • ut_file.precision(2);
  • ut_file << d << endl;

cout << d << endl;

What is the output on the screen? What are the contents of the

file "output.txt"?

2/26/2006 CSI 201 -- Chapter 05 23

The setf and unsetf member functions

A flag is defined to be something that has one of two states,

either on or off (or true or false).

The setf(flag_id) member function will turn a flag on. The unsetf(flag_id) member function will turn a flag off. setf() has a variety of formatting flags you can use to

format your output.

Force all output of letters to be in UPPERCASE. ios::uppercase Show a plus (+) sign before positive numbers ios::showpos Floating point numbers are always written with a decimal point and trailing zeros. If this is not set, then numbers with all zeros after the decimal point might not output the decimal point and zeros. ios::showpoint Floating point numbers are written using the e-notation. Example:

  • 2.78E+03. (Automatically unsets the ios::fixed flag)

ios::scientific Floating point numbers are written in fixed point notation. (Automatically unsets the ios::scientific flag) ios::fixed

2/26/2006 CSI 201 -- Chapter 05 24

Setting a field width and justification

  • width(field_width) member function
  • Sets the field width of the next element in the output stream. (It ONLY

works on the next element!)

  • Example: cout.width(10);
  • Example above sets the field width to 10 characters.
  • If you output something that is larger than the field width specified, the

width of the field is expanded to include the extra characters.

  • ios::right flag (Used with setf)
  • Right justifies the output. When used in combination with the width

function, spaces are padded to the left of the output.

  • ios::left flag (Used with setf)
  • Left justifies the output. Space is padded to the right of the output.
  • NOTE: Book states that setting one of the above flags automatically

unsets the other. This is NOT true! You must call the unsetf() function to unset the flag you don't want to use.

  • If you don't specify justification, the default is right justification.
slide-7
SLIDE 7

2/26/2006 CSI 201 -- Chapter 05 25

ex5.cpp

  • Example:

// Output the average in two different ways...

  • ut_file << "Average:|";
  • ut_file.setf(ios::right);

// Right justified

  • ut_file.width(10);
  • ut_file <<(d1+d2+d3) / 3.0;
  • ut_file << "|" << endl;
  • ut_file << "Average:|";
  • ut_file.unsetf(ios::right);
  • ut_file.setf(ios::left); // Left justified
  • ut_file.width(10);
  • ut_file << (d1+d2+d3) / 3.0;
  • ut_file << "|" << endl;

See ex5.cpp for complete program and actual output…

2/26/2006 CSI 201 -- Chapter 05 26

Manipulators

A manipulator is a special function that can be used in a

sequence of insertion operators to manipulate an output stream.

#include <iomanip> setw(field_width)

Performs the same functionality as the width member function As with the width member function, it only affects the following

item being output on the output stream.

setprecision(p)

Performs the equivalent of the precision member function.

Example using member functions:

cout.precision(2);

cout.width(10); cout << d;

Same example using manipulators:

cout << setprecision(2) << setw(10) << d; 2/26/2006 CSI 201 -- Chapter 05 27

ex6.cpp

double average = (d1 + d2 + d3) / 3.0; // Output the average right justified in a 10 character field

  • ut_file.setf(ios::right);
  • ut_file << "Average:|" << setw(10)

<< average << "|" << endl; // Output the average left justified in a 10 character field

  • ut_file.unsetf(ios::right);
  • ut_file.setf(ios::left);
  • ut_file << "Average:|" << setw(10)

<< average << "|" << endl;

Complete ex6.cpp is on class website…

2/26/2006 CSI 201 -- Chapter 05 28

Examples

  • What do the following examples output?
  • cout << "*";

cout.width(5); cout << 123 << "*" << 123 << "*" << endl; cout << "*" << 123 << "*" << setw(5) << 123 << "*" << endl;

  • cout << "*" << setw(5) << 123 << "*" << 123

<< "*" << endl; cout.setf(ios::showpos); cout << "*" << setw(5) << 123 << "*" << 123 << "*" << endl; cout.unsetf(ios::showpos); cout.setf(ios::left); cout << "*" << setw(5) << 123 << "*" << setw(5) << 123 << "*" << endl;

  • cout << "*" << setw(5) << 1234567 << "*" << 1234567 << "*" <<

endl;

  • Answers given in class…
slide-8
SLIDE 8

2/26/2006 CSI 201 -- Chapter 05 29

Streams as arguments to functions

Like all variables, objects can be passed as

parameters to a function.

This includes stream objects. The function's formal parameter for the stream

must be call-by-reference

Example:

void make_neat(ifstream& messy_file,

  • fstream& neat_file);

2/26/2006 CSI 201 -- Chapter 05 30

ex8.cpp

void make_neat(ifstream& messy_file, ofstream& neat_file, int prec, int field_width) { neat_file.setf(ios::fixed); neat_file.setf(ios::showpoint); neat_file.setf(ios::showpos); neat_file.precision(prec); double next; while (messy_file >> next) { neat_file << setw(field_width) << next << endl; } }

  • This function reads in data from the input file stream "messy_file", and write a formatted
  • utput to the output file stream "neat_file"
  • Pay attention to the boolean expression used in the while loop… this is a handy way of

being able to use a loop to keep reading in data until the end of file has been reached.

  • Explained in class….

2/26/2006 CSI 201 -- Chapter 05 31

Character I/O

The stream library provides low level functions for

reading and writing streams on a character by character basis.

Recall that streams are just sequences of individual

characters.

Output of the number 10 is two characters, '1' and '0',

being sent to the output stream in sequence.

Input of the number 10 is also done as '1' and '0' being

received on the input stream in order.

Interpretation of the sequence of characters '1' and '0'

depends on your program. For example, compare:

  • int x;

char ch1, ch2; cin >> x; cin >> ch1 >> ch2;

2/26/2006 CSI 201 -- Chapter 05 32

istream member function -- get

The istream member function get allows reading

  • f one character from the input and store it in a

variable of type char.

char next_symbol;

cin.get(next_symbol);

Any character can be read in this way, including

numbers, letters, punctuation, space, newline, tab, etc…

If you wanted to write a program that read in and

echoed EXACTLY what the user typed in, including all whitespace characters, you would need the get() member function.

Why couldn't you use the extraction operator >> ?

slide-9
SLIDE 9

2/26/2006 CSI 201 -- Chapter 05 33

ex9.cpp

int main() { char ch; cout << "Enter input. Enter the letter 'z' as your last character.\n"; cout << "First, I'll read in your input using the >> operator:\n"; do { cin >> ch; cout << ch; } while (ch != 'z'); cout << "\nNow, I'll read it in using the get() function: \n"; do { cin.get(ch); cout << ch; } while (ch != 'z'); cout << endl; }

What is the output of this program on the following input: 1b4 $5 z

2/26/2006 CSI 201 -- Chapter 05 34

Example

char c1, c2, c3;

cin.get(c1); cin.get(c2); cin.get(c3);

You type in the following:

A B C

What is the value of c1, c2 and c3?

2/26/2006 CSI 201 -- Chapter 05 35

Newline character

We've seen the \n character inside of strings.

cout << "Please enter your age:\n";

The newline character is an actual character than can be

stored in a char variable just like other characters:

We can test for a newline character:

  • char ch;

cout << "Please enter a character, then press ENTER "; cin.get(ch); if (ch == '\n') cout << "You didn't enter anything!\n"; else cout << "Thank you.\n";

if (ch == "\n") was used, it would fail to compile,

because of incompatible types. (One character between double quotation marks still has a string type!)

2/26/2006 CSI 201 -- Chapter 05 36

  • stream member function -- put
  • stream has a member function called put

that is analogous to the member function get except that it writes a single character to the

  • utput stream.

It takes a single argument of type char. cout.put('a');

cout.put('\n');

slide-10
SLIDE 10

2/26/2006 CSI 201 -- Chapter 05 37

Example

char next;

int count = 0; cin.get(next); while(next != '\n') { if ((count % 2) == 0) cout << next; count++; cin.get(next); } cout << "\ncount = " << count << endl;

What is the output of this program based on the following input?

abcdef gh 2 4 6 8 10 12 2/26/2006 CSI 201 -- Chapter 05 38

The eof member function

Member function eof detects the end of a file

ifstream member function eof stands for end of file eof returns a bool type

true when the end of the file has been reached false when there is more data to read

Normally used to determine when we are NOT

at the end of the file

Example:

if ( ! in_stream.eof( ) ) in_stream >> data;

2/26/2006 CSI 201 -- Chapter 05 39

Using eof

  • This loop reads each character from the input stream, and writes the

character to the screen in_stream.get(next); while (!in_stream.eof( ) ) { cout << next; in_stream.get(next); }

  • The end of a file is indicated in the file by a special character, called

the EOF character, or end-of-file character.

  • in_stream.eof( ) becomes true when the program reads past

the last character in the file, thereby reading the EOF character.

  • in_stream.eof( ) is still false after the last character of data is

read

  • in_stream.eof( ) becomes true when the special end of file

character is read

2/26/2006 CSI 201 -- Chapter 05 40

Testing for end of file – two methods

  • We have seen two methods to test for the end of file:
  • while ( in_stream >> next)
  • while ( ! in_stream.eof( ) )
  • Which should be used? In general:
  • If you're using get(ch) (or other) member function, then use eof()
  • If you're using the extraction operator (>>) to read data, use the extraction
  • perator method. (Particularly useful when processing numeric data.)
  • NOTE: On UNIX systems, eof() won't return true until the EOF

character has actually been read. On other systems, sometimes eof() returns true when the EOF character is the next character to be read.

  • For this course, you should assume the behavior of eof() as described in

the book and in these slides, where eof() will not return true until the EOF character has be read.

  • Moral of the story - If you are running your program on different operating

systems (e.g. Windows), be sure to test!

  • NOTE: On UNIX systems, if your program is reading from the keyboard,

you can usually simulate an EOF character being sent to your program by pressing <CTRL>-D when your program is waiting for input.

slide-11
SLIDE 11

2/26/2006 CSI 201 -- Chapter 05 41

The ignore istream member function

cin.ignore(int n,char delimiter);

Read and discard characters from an input stream.

The function returns when either n characters are read in, or the

delimiter character is read.

Why would you want this?

If you wanted to read and discard all input up to where the user

hit enter, you could simply call:

  • cin.ignore(1000,'\n');
  • Here, 1000 is just an arbitrary large number

Suppose you want to read only the first character in the input

stream, and discard everything thereafter:

  • char ch;

cin.get(ch); cin.ignore(1000,'\n');

Now, you know your input stream is empty, and you can start

from a known state.

You can use this with any istream object, not just cin.

2/26/2006 CSI 201 -- Chapter 05 42

Predefined character functions

  • #include <cctype>
  • The following functions can test characters
  • isupper(char_exp)
  • islower(char_exp)
  • isalpha(char_exp)
  • isdigit(char_exp)
  • isspace(char_exp)
  • The following functions convert characters between upper and lower

case

  • int toupper(char_exp)
  • int tolower(char_exp)

2/26/2006 CSI 201 -- Chapter 05 43

Be careful with cctype functions

All cctype functions are declared to take

arguments of type int, not char.

The functions toupper and tolower also return

an int, not a char.

cout << tolower('A');

  • utputs the number 97

To force the expression to be evaluated as a char

type, use the static_cast<char> clause, introduced in Chapter 3:

cout << static_cast<char>(tolower('A'));

  • utputs the letter a

2/26/2006 CSI 201 -- Chapter 05 44

ex10.cpp

int main() { char ch; cout << "Enter a character for me to test: "; cin >> ch; if (isupper(ch)) { cout << "Converting to lowercase...\n"; cout << "Without cast: " << tolower(ch) << endl; cout << "With a static_cast<char>: " << static_cast<char>(tolower(ch)) << endl; } else if (islower(ch)) { cout << "Converting to uppercase...\n"; cout << "Without cast: " << toupper(ch) << endl; cout << "With a static_cast<char>: " << static_cast<char>(toupper(ch)) << endl; } else cout << "Your input was neither an upper or lower case letter!\n"; }

  • What does this program output with the following input?
  • a
  • A
  • 2
slide-12
SLIDE 12

2/26/2006 CSI 201 -- Chapter 05 45

More on object-oriented programming

  • In the "real world", we often find ourselves with existing classes that

perform most of what we want, but lacks some functionality we need for our design.

  • Inheritance is the process by which we can define new classes that

are based on existing classes

  • Prevents us from needlessly rewriting code that already does what

we want.

  • Why reinvent the wheel? - Inheritance is a very powerful feature of
  • bject oriented programming, and is the biggest reason that OOP

has become so popular in software development today.

  • We can define a new class that is derived from the existing class.
  • The new class is sometimes referred to as the child class of the

existing class, where the existing class is referred to as the parent class or base class.

  • The new class is also sometimes referred to as a subclass, where

the existing class is referred to as the superclass.

2/26/2006 CSI 201 -- Chapter 05 46

Inheritance among stream classes.

  • cin is an object of type istream.
  • cout is an object of type ostream.
  • istream and ostream contain all the functionality we need for dealing with

streams, but lack functionality for dealing with streams coming from or being sent to files.

  • So, don't write completely new classes for dealing with files – build on what

has already been designed!

  • ifstream and ofstream are standard C++ library classes for dealing with

file I/O that are based on the classes istream and ostream, respectively.

  • ifstream is derived from istream.
  • ifstream inherits istream's functionality for processing input streams.
  • ifstream adds functionality for dealing with reading files.
  • fstream is derived from ostream.
  • fstream inherits ostream's functionality for processing output

streams.

  • fstream adds functionality for dealing with writing files.

2/26/2006 CSI 201 -- Chapter 05 47

The beauty of inheritance…

  • Inheritance prevents us from needing to write different functions for different classes of the same

family.

  • Let's go back to our hello world program. This version neglects inheritance, using two functions:

void hello_file(ofstream &out_stream) {

  • ut_stream << "Hello, World!\n";

} void hello_out(ostream &out_stream) {

  • ut_stream << "Hello, World!\n";

} int main() {

  • fstream out_file;

hello_file(out_file); hello_out(cout); }

  • But, one function will accomplish what we need!

void hello(ostream &out) {

  • ut << "Hello, World!\n";

} int main() {

  • fstream out_file;

hello(out_file); hello(cout); }

2/26/2006 CSI 201 -- Chapter 05 48

Why does inheritance work?

  • (Inheritance will be explained in class…)
  • An object that is declared of a derived type can also take on the base type.
  • In OOP, we refer to this concept as polymomrphism.
  • Therefore, when declaring a formal parameter to be the type of a base class, it can accept

actual parameters of that class, as well as of derived classes.

  • But, this does not work the other way around: A child type parameter can NOT take on the

type of a parent!

  • Example:

void hello(ofstream &out) {

  • ut << "Hello, World!\n";

} int main() {

  • fstream out_file;

hello(out_file); hello(cout); // <-- Illegal! Won't compile! Error will occur here! }

slide-13
SLIDE 13

2/26/2006 CSI 201 -- Chapter 05 49

ex11.cpp -- Encryption

  • Complete file presented in class…
  • The focus of the program is on the encryption function:

void encrypt(int shift, istream& in_stream, ostream& out_stream) { char next; in_stream.get(next); while (! in_stream.eof( )) { next = toupper(next); if (isalpha(next)) { next += shift; if (next > 'Z') next -= 26; }

  • ut_stream << next;

in_stream.get(next); } }

2/26/2006 CSI 201 -- Chapter 05 50

ex11.cpp

To use the encrypt function with files, we can call it as follows:

ifstream fin;

  • fstream fout;

encrypt(10,fin,fout);

  • r, if we want to make the user type in their input from the

keyboard and display the output to the screen: encrypt(10,cin,cout);

Both work because encrypt's formal parameters are of type

istream and ostream.

2/26/2006 CSI 201 -- Chapter 05 51

Default arguments for functions

You can specify a default parameter value in the

function declaration.

Example:

  • void encrypt(int shift, istream& in_stream = cin,
  • stream& out_stream = cout);

If the arguments for in_stream and out_stream

aren't specified in the function call, then the compiler assumes the default arguments.

You may also specify default parameters in the

header of the function definition, but this is not necessary.

2/26/2006 CSI 201 -- Chapter 05 52

Example:

  • void test(int a, int b, int c = 3, int d = 4)

{ cout << a << ' ' << b << ' ' << c << ' ' << d << ' ' << endl; } Does each of the following compile properly?

If so, what is the output generated?

test(0,1,2,3); test(10,9,8); test(1,2); test(1); test();

slide-14
SLIDE 14

2/26/2006 CSI 201 -- Chapter 05 53

The End