60
Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output Object-Oriented Principles and Practice / C++ Lecture 2 Alice E. Fischer January 30 & February 6, 2018 OOPP / C++ – Lecture 2. . . 1/60

Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

  • Upload
    others

  • View
    3

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Object-Oriented Principles and Practice / C++

Lecture 2

Alice E. Fischer

January 30 & February 6, 2018

OOPP / C++ – Lecture 2. . . 1/60

Page 2: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Standards

Compiler and Linker

C++ Program Structure

OO Thinking

Input and Output

OOPP / C++ – Lecture 2. . . 2/60

Page 3: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Course Programming Standards

OOPP / C++ – Lecture 2. . . 3/60

Page 4: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Five Commandments for this CourseRead and think about Chapter 1 of Exploring C++

1. Use C++ input and output, not C I/O for all assigned work.

2. Don’t use global variables. If you think you need one, yourclass-design is probably defective. Ask for help.

3. Test every line of code you write. It is your job to prove to methat your entire program works. If I get a program without atest plan and output, I will assume that it does not compile.A program with a partial or inadequate test plan will beassumed to be buggy.

4. Clean up after yourself. Close files. Delete dynamic memory.

5. Put your name and the file name in comments at the top ofevery file.

OOPP / C++ – Lecture 2. . . 4/60

Page 5: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Basic Design Principles and Standards

1. * Conform to the specifications.

2. * Keep it simple.

3. * Make your code readable.

4. * Identify the expert for each task.

5. * Maintain data privacy. Use delegation.

6. Maximize data isolation: use const wherever meaningful.

7. Know what object has custody of dynamic memory areas atall times.

8. Avoid hardware- or OS-dependent code.

* These topics are elaborated in the following slides.

OOPP / C++ – Lecture 2. . . 5/60

Page 6: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Conform to the SpecificationA product is worthless if it does not do what the client ordered.

1. In this course, PLEASE read the instructions. Read all of theinstructions before you begin to write code. Take the time tounderstand what you are supposed to do.

2. Code design takes time but it makes code production muchfaster and easier. Take the time to understand the classstructure you are trying to implement.

3. In this course, the assignments are designed to give youpractice using a wide range of tools. Use the tools andtechniques that are required. You might find somethingdifferent on the internet, but that is irrelevant. (You are wisernot to search for solutions “out there”.)

4. If you think my specification is wrong, ask. Don’t just ignoreit.

OOPP / C++ – Lecture 2. . . 6/60

Page 7: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Keep it Simple

CAN is not the same as SHOULD.

1. A function is too long if it does not fit on your screen all atonce.

2. A function is not simple if its logic is nested to level 4 or more.

3. A function is not simple if I cannot comprehend its purposeand action in 30 seconds.

4. Very long and very short identifiers are not simple.

5. A name is not simple if you cannot pronounce it.

6. A class name that is the same as a variable name is notsimple. Avoid it.

OOPP / C++ – Lecture 2. . . 7/60

Page 8: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Make your code readable

1. Minimize the use of underscores and variable names i, l, andO. Remember – my eyes cannot see fine detail. Use letters Ican see (j, k, n).

2. Put a space after every comma or semicolon.Donotwritecodethatlookslikethis.

3. Use blank lines to divide code into paragraphs. DO NOT USETHEM EVERYWHERE.

4. Indent your code properly. Xcode and Eclipse will do this foryou.

5. Restrict code and comments to 80 columns. Avoid namesthat are so long that you cannot do this.

6. Put a divider-comment before the first line of every function.

7. PLEASE put the opening { on the same line as the if or foror function name.

OOPP / C++ – Lecture 2. . . 8/60

Page 9: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Identify and Rely on the Expert

1. The expert on type A objects is class A.

2. All functions that work on type A objects belong in this class.item All changes to type A objects should be done byfunctions in class A.

3. A class definition defines ONE object of that class. Functionsthat operate on ONE object, or binary operators that operateon two belong in the class.

4. Function that operate on many of these objects belong in adifferent class.

OOPP / C++ – Lecture 2. . . 9/60

Page 10: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Maintain Data Privacy

1. All member variables and class variables should be private orprotected.

2. Read-only access can be supplied by “getters”.

3. “Setters” breach privacy. Do not use them in this class.

4. The class constructor(s) should store data in a new classobject. Don’t call the constructor until you know what datashould be used.

OOPP / C++ – Lecture 2. . . 10/60

Page 11: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

The Compilation Model

I Traditionally, C and C++ are compiled one module (one .cppfile) at a time, producing .o files.

I However, the clang compiler compiles all modules together inorder to improve optimization.

I Next, the .o files are linked with each other and with thesystem libraries to form an executable.

I The compiler cannot succeed if the same class or typeinformation is included twice in the same compile module.(double inclusion).

I The linker cannot succeed if:I a symbol is used in one module but never defined in any of the

.o files being linked.I the same symbol is defined twice in a project.

OOPP / C++ – Lecture 2. . . 11/60

Page 12: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Code Modules

This application has a main program and three code modules:Graph, Row, and Item. It uses the tools.

row.hpp

main.cpp

graph.hpp

graph.cpp row.cppSource code files

Header files item.hpp

tools.cpp

tools.hpp

Uses graph, tools

Defines graph Defines row Defines item

Uses graph, row, tools

Uses row, item, tools

Defines tools

Uses tools

Uses tools

OOPP / C++ – Lecture 2. . . 12/60

Page 13: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Compiled

Each module is compiled separately.Compilation produces an object file (.o file).

g++ -c -Wall graphM.cpp

row.o

row.hpp

graphM.cpp

graphM.o

g++ -c -Wall row.cpp

graph.hpp

graph.cpp row.cpp

g++ -c -Wall graph.cpp

graph.o

Source code files

Header files

Object files

Compilation steps

tools.o

item.hpp

g++ -c -Wall tools.cpp

tools.cpp

tools.hpp

OOPP / C++ – Lecture 2. . . 13/60

Page 14: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Linked

The object files are sent to the linker, which connects them.It also links in any system libraries that you have used.The result of linking is an executable program.

g++ -c -Wall graphM.cpp

row.o

row.hpp

graphM.cpp

graphM.o

g++ -c -Wall row.cpp

g++ -o graph -Wall graphM.o graph.o row.o tools.o

graph

graph.hpp

graph.cpp row.cpp

g++ -c -Wall graph.cpp

graph.o

Source code files

Header files

Object files

Executable file

Compilation steps

Linking step

tools.o

item.hpp

g++ -c -Wall tools.cpp

tools.cpp

tools.hpp

OOPP / C++ – Lecture 2. . . 14/60

Page 15: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Program Structure

Chapter 4.1 of Exploring C++

I A simple 1-class C++ program has three files:

1. One file contains the main function, some unit-test functions,and very little else.

2. One file is the header for the class. It contains the classdeclaration, list of data members, definitions of inlinefunctions, and prototypes of the functions that are too long tobe inline.

3. The third file contains the definitions of the functions thatwere prototyped in the header file.

I In today’s example, these files are main.cpp, pack.hpp,and pack.cpp.

OOPP / C++ – Lecture 2. . . 15/60

Page 16: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

The Main Program

I The main() function is not part of a class. (Unlike Java.)

I Its prototype is one of these:int main( void )

int main( int argc, char* argv[] )

I Include the header file for your major class in this file.

I The main function should call banner() and bye()

I Between these calls, it must create an object of the primaryapplication class (say, Cls).

I In a completed application, main() will then call Cls.run().

I However, when building an application, main() is used to calla series of unit test functions.

OOPP / C++ – Lecture 2. . . 16/60

Page 17: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Unit Tests.

The file that contains the main() function should also contain aseries of unit test functions.

I There should be one unit-test for each week’s assignment(each class or pair of classes).

I A unit test should call every public function in itscorresponding class, one or more times.

I Choose a sequence of calls that causes every line of code inthe class to be executed, including the private functions, ifany.

I If you put main() at the bottom of the file, you don’t need towrite prototypes for all the unit tests.

OOPP / C++ – Lecture 2. . . 17/60

Page 18: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Header Files

I Each code module has its own header file that containsinformation needed at compile time.

I Most header files are included in two or more modules.Tools is included in many.

I When you include a header file, its contents are copied intoyour current compile module and supply type informationabout the functions in the same or another module. Thisinformation is necessary for the compiler to typecheck everyfunction call.

OOPP / C++ – Lecture 2. . . 18/60

Page 19: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

The Header File.

I The #pragma once compiler directive is used to make surethis header file is not included twice in any compile module.

I This does NOT prevent circular #includes, which are dealtwith another way.

I At the top, #include "tools.hpp" and all otherprogrammer-defined header files that will be needed by thisclass.

I Keep in mind that the tools header includes the line using

namespace std;

OOPP / C++ – Lecture 2. . . 19/60

Page 20: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

The tools.

Please go over tools.hpp and included functions such as fatal.

I fatal( "Error: %s not open.\n", fname.data());

I banner()

I bye()

I >> flush

To learn something interesting, study the the way that fatal() isimplemented.

OOPP / C++ – Lecture 2. . . 20/60

Page 21: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

#include Files.

I A code module can only ”see” the header files that itincludes. Therefore, the .cpp file for each module mustinclude its matching .hpp file.

I The .hpp file for each module should include all the other .hppfiles that the code uses.

I In this class, I have asked you to #include tools.hpp anduse a few of the tools. The version of tools for this class isdifferent from all previous versions for other classes. I haveremoved the training wheels and left only enough functions tosupport specific goals for this class.

I You will be expected to learn and appropriately #include anystandard headers that your code needs.

I You will also include your own header files in many modules.

OOPP / C++ – Lecture 2. . . 21/60

Page 22: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

#include Problems

I Failure to include: A code module can only ”see” the headerfiles that it includes. If you use a function from a differentmodule, you must include its header. This condition may alsobe caused by a circular include.

I Double inclusion: You must not include a header twice in thesame module. Use include guards to prefent this: #ifndef

...#define and #endif OR #pragma once .

I #pragma once is easier but not officially standard. However,every system we know about understands it.

OOPP / C++ – Lecture 2. . . 22/60

Page 23: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Circular Includes

I Suppose you have two modules called Mom and Kid. In yourapplication, they work together. So you include mom.hpp inkid.hpp and vice versa. This is a circular include.

I Assume that you have installed proper include guards in bothheader files. Then in one module or the other, the guards willprevent the inclusion of a file where it is needed:

I Say you are compiling Mom. Mom includes Mom.hpp whichincludes Kid.hpp which includes Mom.hpp . . . and thecompilation fails.

I This problem shows up as a function that is not defined, whenyou can clearly see that you defined it.

OOPP / C++ – Lecture 2. . . 23/60

Page 24: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

The Class Declaration: in the .hpp fileI The first line of the class declaration gives the class name

followed by an open-brace. Note the ; after the matchingclose-brace. (Like a C struct, unlike a Java class.)

I Inside the class definition are the private and public

parts. You usually only need to write these keywords once perclass (unlike Java).

I I like to see the data members at the top, functions below.I Initialize the data members here, if the initial value is known

at compile time.I The public functions provide an interface to the world and

control all access to the data members.I Minimally, define a constructor and a print() function for

every class. Also define a destructor if any part of the classallocates dynamic memory.

OOPP / C++ – Lecture 2. . . 24/60

Page 25: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Inline Functions: in the .hpp file

Short functions, defined in the header file are compiled inline.

I Every time an inline function is called, the compiler removesthe call and inserts the entire body of the function in itsplace, with the parameter references replaced by argumentvalues. (Like expanding a macro).

I Unlike macro expansion, this is done with full parametertype-checking and type conversion, if needed.

I There is no stack frame, no jump-to-subroutine, no return.

I This is very time-efficient and is also space-efficient if thefunction body is short.

I Functions that contain control statements are not expandedinline.

OOPP / C++ – Lecture 2. . . 25/60

Page 26: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Constructors: in the .cpp file

I A constructor has the same name as the class.

I Put it in the header file if it one line. Otherwise, theprototype goes in the header file and the function definitiongoes in the .cpp file.

I Its purpose is to initialize objects of that class when they arecreated by some other class.

I Many constructors don’t construct anything – they justexecute a bunch of assignments.

I Normally, a constructor will have parameters. Its code willcopy those parameter values into the corresponding classmembers.

I Class members that do not correspond to parameters areinitialized by some computation based on a parameter.

OOPP / C++ – Lecture 2. . . 26/60

Page 27: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

The Destructor: in the .hpp or .cpp file

I The name of a destructor is a tilde followed by the class name.

I Put it in the header file if it is short. Otherwise, the prototypegoes in the header file and the function definition goes in the.cpp file.

I Its job is to free any dynamic memory, attached to the dyingobject, that was allocated by the constructor or any otherclass function.

I If there IS no dynamic memory in the object, you don’t need adestructor.

I However, good style says you should write simple applicationsthe same way as complex apps. So write a default destructor:∼Person() = default;

OOPP / C++ – Lecture 2. . . 27/60

Page 28: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

The .cpp file Implements the Class Functions

Non-inline functions are written in the Classname.cpp file.

I At the top, #include ONLY the header file for the class.

I The exception to this rule is complex situations in which youneed to break a circular #include.

I Please start each function definition with a dashed commentline. Do this out of respect for me, and because you realize Ihave a lot of trouble seeing things.

I Each function definition must include the name of the class,between the return type and the function name:

//----------------------------------

void Person::print(){...}

OOPP / C++ – Lecture 2. . . 28/60

Page 29: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Print Functions

I To debug a class, you have to be able to see the data in itsobjects.

I For this purpose, you will define a function named print()

for every class you write.

I The print() function will format and print all of the datamembers of the class.

I Use this pattern for your print functions:ostream& print( ostream& out ){

out <<mem1 <<" \t" <<mem2 <<endl;

return out;

}

OOPP / C++ – Lecture 2. . . 29/60

Page 30: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

OO Principles and OO Design

OOPP / C++ – Lecture 2. . . 30/60

Page 31: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

The main function.

I Main is called by the operating system and returns to the OS.

I Its job is to interface with the OS, then instantiate the primaryobject of the application, and transfer control to that object.

I Main often handles and validates the command-linearguments.

I It sometimes opens files.

I Doing everything in main is simply harder than using classes,and harder to debug and maintain.

I So, in general, get out of main asap.

OOPP / C++ – Lecture 2. . . 31/60

Page 32: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Class vs. struct

I C supports struct, not class, and has only data members in astruct.

I C++ supports both (for compatibility) and the C++ structcan have methods and constructors, like classes.

I The only difference is the default protection level: classesdefault to private, structs default to public.

I Use classes.

OOPP / C++ – Lecture 2. . . 32/60

Page 33: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Constructors

I A constructor defines the initialization rules for a class. It mayor may not construct dynamic parts of the class.

I If a constructor is not supplied, the compiler willautomatically supply a null default constructor.

I However, it is good practice to be explicit about things, anddefine a constructor, even if it is a default constructor.

I The old way was to write: Classname(){} in the header file.

I The modern syntax is: Classname() = default;

I The default constructor belongs entirely in the .hpp file.

I Many classes have two or more constructors.

OOPP / C++ – Lecture 2. . . 33/60

Page 34: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Constructor DetailsConstructors are commonly used in these ways:

I A single object in the current stack frame:BT data;

I A single object using non-default constructor:BT data( params );

I A single object dynamic memory:BT* datap = new BT

I A dynamic memory using non-default constructor:BT* datap = new BT( params)

I An array in the current stack frame, using default constructor:BT data[max];

I An array in dynamic memory, using default constructor::BT* datap = new BT[max]

OOPP / C++ – Lecture 2. . . 34/60

Page 35: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Default Parameters

Any function can have default parameters. They are very commonin constructors. DataPack(string filename, int len = LENGTH);

I All required parameters must come first.

I The default parameter(s) that follow permit you to call thefunction with fewer parameters.

I A prototype or inline function must declare the defaultparameter in the .hpp file.

I Default parameters are in the header file because thisinformation must be known at compile time.

I The default values may be omitted in the .cpp file. If they arepresent, they must match.

OOPP / C++ – Lecture 2. . . 35/60

Page 36: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Destructors

The purpose of a destructor is to delete all the dynamic parts thatare attached to a class instance.

I The destructor is run when an object goes out of scope orwhen you call delete or delete[].

I The code in a destructor is normal code. Destructors oftencontain loops.

I delete is used for non-array dynamic objects.

I delete[] is used for dynamic objects that are arrays.DataPack(){ delete[] data; }

It first deletes the elements in the array, then frees the arrayitself.

OOPP / C++ – Lecture 2. . . 36/60

Page 37: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Privacy.

I How does private differ from protected and public?public allows any part of the program to change variables.public allows any part of the program to call functions.private allows only access only to other parts of the class.protected is only relevant when class derivation is used.

I Why do we have private variables?To allow a class to protect its instances from tampering.To make plug-and-play programming possible.

I Why do we have private functions?They are helpers for the public functions.They are no business of any outside class.

OOPP / C++ – Lecture 2. . . 37/60

Page 38: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Inline functions

When an inline function is called, the compiler copies thefunction’s code into the caller, in place of the function call.

I What is the point of inline functions?To do simple things simply.To speed up execution.

I What functions are inline:Anything defined within the {. . . } of the class declaration.Any function definition in the .hpp file, after the end of theclass, that starts with “inline”.

I How does an inline function differ from other functions?It must be entirely in the .hpp file because all of it isneeded to compile a client class.

OOPP / C++ – Lecture 2. . . 38/60

Page 39: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Other functions

When a non-inline function is called, a new frame is built on theruntime stack. Then a jump-to-subroutine happens, and later, areturn.

I Longer functions are declared in a .cpp file.

I Each definition in the .cpp must have a prototype in the .hpp.The details must be the same.

I Each definition in the .cpp starts with the name of the class itbelongs to:

MyClass:: print(ostream& out){ ... }

I You could put all the function definitions for all the classes inone .cpp file. However, that would not be good style.

OOPP / C++ – Lecture 2. . . 39/60

Page 40: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

C++ Streams and IO

OOPP / C++ – Lecture 2. . . 40/60

Page 41: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Hello C++

Chapter 3: Converting C I/O skills to C++

I Sections 3.1 – 3.5 provide a look-up table for C programmerswho want to translate their C knowledge to C++.

I We will go through this chapter in detail a little bit at a time.

I However, the second programming assignment requires just alittle bit of C++ input and output knowledge.

I So we look very briefly at the few things you need to knownow.

OOPP / C++ – Lecture 2. . . 41/60

Page 42: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

The Stream Hierarchy

The stream classes in C++ form a polymorphic hierarchy, witheach level derived from the level above it.

ios

istream ostream

ofstreamifstream fstream

ios_basestreambuf

iostream

ostringstreamistringstream stringstream

Any function or constant defined anywhere in this hierarchy can beused where it is defined or at any level below that.

OOPP / C++ – Lecture 2. . . 42/60

Page 43: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

The Stream Hierarchy

I ios_base defines the constants and error flags that arecommon to all streams.

I ios combines these core definitions with an implementationof buffering.

I istream, ostream are used to define cin and cout. Thesestreams are line-buffered. The iostream class is for use withrandom-access files, such as databases.

I Streams built on files ifstream, ofstream are buffered inlarge blocks (disk clusters).

I A stringstream is an array that imitates a file. Like anystream, a stringstream is used with the stream operators andfunctions.

OOPP / C++ – Lecture 2. . . 43/60

Page 44: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Standard Streams

During execution, a stream is implemented by a structurecontaining buffers, error flags, cursors, and more.

Four streams are automatically allocated and opened for a processwhen it begins execution:

I cin (like stdin in C) is an istream

I cout (like stdout) is an ostream. Both of these are buffered.

I cerr is an unbuffered ostream (like stderr in C). Use cerr foroperator instructions, error messages, and debugging output.

I clog is an unbuffered ostream. Use it if your applicationrequires logging transactions or errors.

OOPP / C++ – Lecture 2. . . 44/60

Page 45: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Opening a StreamChapter 2, page 20, center

I To open a file stream, use ifstream or ofstream.

I If possible, declare and open the stream on the same line ofcode:

ifstream myInput( "data.txt" );

ostream myOutput( "data.txt", ios::app );

I If the file name is not known at the time the stream isdeclared, use the open command:

myInput.open( "data.txt" );

I To open an output stream in append mode:myOutput.open( "output.txt", ios::app );

I Always check for proper opening:if ( !myInput.is_open() ) fatal(...);

OOPP / C++ – Lecture 2. . . 45/60

Page 46: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Testing the State of the Stream

I if( !inStrm.is_open()) fatal(...);

Test if stream is open immediately after opening it.

I if( inStrm.good() )

After reading from a stream, test if you got good data.False if eof, or if hardware failed, or conversion failed.

I if( inStrm.fail()) )

True if there was a conversion error during a numeric read.False if good data was read and also if eof happened.

I if( inStrm.eof() ) break;

AFTER reading from stream, test if end-of-file happened.Always after a read, not before.

I inStrm.clear();

Do this after an error before the stream will function again.

OOPP / C++ – Lecture 2. . . 46/60

Page 47: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Stream ManipulatorsA stream manipulator changes the state of the stream, but it is notexactly a function. They are written within the chain of >>operators. The most important examples are:

I ws : Read and remove chars from the input stream until avisible char is found.

I noskipws : DO NOT skip ws until this is reset.

I endl: Flush the output buffer.

I flush: For output, write the contents of the output buffer toits destination file or screen.

I flush: Read and discard the rest of the line in the inputbuffer. (Defined by tools.)

I ignore(n) : Read and discard up to n keystrokes. Stop at endof line, if that happens sooner.

OOPP / C++ – Lecture 2. . . 47/60

Page 48: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Output: in the .hpp and cpp files

Refer to main.cpp and the definition of print() in pack.cpp.

I C++ knows how to format all the built-in types.

I To print a numeric or string value, just send it to an outputstream:cout << k <<" " << ary <<"\n";

I Multiple fields can be printed with one line of code.

I Remember to output spaces after each data item.

I Remember to put a newline on the end. Output does not goto the screen until that bkn

I You can also use endl to end a line.cout << k <<" " << ary <<endl;

I Formatting floats in C++ involves much detail.

OOPP / C++ – Lecture 2. . . 48/60

Page 49: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Using an Output Stream

Chapter 3, page 23. (We will cover formatting later.)

I Use << to send output to cout, cerr, clog, and any ofstream

or ostringstream .

I Use << for numeric output, chars, strings, and objects.

I You may chain several << in one statement, but remember toadd spaces between your data items:cout <<name <<"\t" <<email <<endl

I Writing endl will terminate a line and always flush the buffer.

I Writing "\n" will terminate a line and flush the cout buffer. Itwill not flush the buffer for an ofstream.

OOPP / C++ – Lecture 2. . . 49/60

Page 50: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

The Output Operator: in the .hpp file

One design goal for C++ was to be able to use a class object inthe same ways that predefined objects can be used.

I So we want to read and write class objects using >> and <<.

I We are able to define new methods for global operators, andwe normally do define a method for << for each new class.

I The general form of this definition is:

inline ostream&

operator<<( ostream& out, Class& obj) {

return obj.print( out );

}

I Place this definition inside the .hpp file after the }; thatterminates the class.

OOPP / C++ – Lecture 2. . . 50/60

Page 51: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Operator <<The output operator is an overload of the left-shift function in C.

I When you define the operator for your own class, thedefinition is an extension of the global overload that allowsyou to use << to print a class instance.

I It belongs WITH the class but cannot be in the class but itcannot be IN the class because the first operand must be anostream.

I A global function cannot access private data parts, but it cancall the public print() function. The print function in theclass can handle the private parts. So operator << calls thepublic print function to get the job done.

I The stream parameter must be returned. That is what allowsyou to write a chain of << in one output statement.

I A space between the word and the << is optional.

OOPP / C++ – Lecture 2. . . 51/60

Page 52: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

C++ Output Formatting

Using these helps to appreciate the convenience of C formats!

I Column width: must be set for every output field.<< setw(5)

I Justification: remains set until changed.<<left or <<right

I Fill character: remains set until changed.setfill(’-’)

I Number base for I/O conversions: hex or dec

I Precision: setprecision(2)

I Notation: fixed for %f or scientific for %e.Use general; to return to the default %g notation. Remainsset until changed.

OOPP / C++ – Lecture 2. . . 52/60

Page 53: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Newline and endl

I Does \n work in Windows (where the line endings are \r\n)to write an explicit newline?

cout<< "Construction complete\n";)

Yes. The C/C++ compiler converts the \n in strings to theappropriate line endings for the platform it is running on.

I \n causes a non-file ostream to be flushed immediately. .

I \n does NOT flush the ofstreams immediately. The contentswill be flushed when the buffer is full.

I endl flushes both kinds of stream immediately. This is finefor the screen but bad for files.

OOPP / C++ – Lecture 2. . . 53/60

Page 54: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Stream Ties and Stream Merging

I cin is tied to cout.When you change from output to input, the output stream

is flushed.

I cout is merged with stdout.When you mix C and C++ output, the screen will show

the outputs in time-order.

I cin is merged with stdin.If you alternate reading from the two streams, you will read

the data in the same order it was entered.

OOPP / C++ – Lecture 2. . . 54/60

Page 55: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Output Confusions

I Why use an & when passing a stream parameter?

I What is cerr?A non-buffered output stream that goes by default to thevideo screen. Mixes with cout.

Intended for operator instructions and error messages.Used also for debugging output.

I Why use an ostream& parameter in your print functioninstead of just cout?

print( ostream& out )

It adds flexibility. What if you want to write to a file?

OOPP / C++ – Lecture 2. . . 55/60

Page 56: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Using an Input Stream

Chapter 3, page 22.

I Any kind of istream can be read using the input operator >>,including an ifstream or a istringstream.

I Use >> for numeric input or chars.

I By default, cin >> skips leading whitespace before reading anumber or a char.

I To read a single character into ch, writecin >> ch; or ch = cin.get()

I To remove unread chars from cin, use cin >> flush;

I To remove a fixed number of unread chars from cin, usecin >> ignore(1);

OOPP / C++ – Lecture 2. . . 56/60

Page 57: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

C++ string Input

I To read a string into a C++ string named str, then discardthe newline:

getline( cin, cppStrVar);

I Read up to but not including a comma:getline( cin, cppStrVar, ’,’ );

I To get the c-string out of the C++ string:char* cstr = cppStrVar.data();

char* cstr = cppStrVar.c_str();

OOPP / C++ – Lecture 2. . . 57/60

Page 58: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

C++ input into a char array is much more complicated.

Read a string into char ary[30] and append a null-terminator:

I Use get() or getline for cstring input where whitespaceshould be read and kept.

I Read to end of line, leave newline in the stream:cin.get( ary, 30 );

I Read to end of line, remove and discard newline:cin.getline( ary, 30 );

I Read up to a comma and leave it in the stream:cin.get( ary, 30, ",");

I Read up to a comma and discard the comma:cin.getline( ary, 30, ",");

OOPP / C++ – Lecture 2. . . 58/60

Page 59: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Use these things wisely:

I Always use a length limit when reading a C-string.

I This is irresponsible because the input can be longer than thearray. It reads chars, up to the first space: :

cin >> str; // BAD! Do not use this.

I Before calling get() or getline() to read a string, removeleading whitespace:

cin >> ws;

I If you DO NOT want to skip leading whitespace:cin >> noskipws;

I Immediately after a get or getline, the function gcount()

will return the actual number of characters read and removedfrom the istream. (No need to call strlen() anymore.)

OOPP / C++ – Lecture 2. . . 59/60

Page 60: Object-Oriented Principles and Practice / C++ [1ex]Lecture 2

Outline Standards Compiler and Linker C++ Program Structure OO Thinking Input and Output

Input Misconceptions

Where did these faulty beliefs come from?

I Normally you would check for EOF before reading in an item.

I Using the standard flush will empty out the input that isalready in the stream but not yet read. The tools librarycontains a defiinition of flush that works on input sstreams.

I The right way to read a line of data is to read the whole lineand parse it yourself.

OOPP / C++ – Lecture 2. . . 60/60