33
January 26, 2012 CS410 – Software Engineering Lecture #2: Hello, C++ World! 1 C++ Overview C++ Overview History and major features of C++ History and major features of C++ Input and output Input and output Preprocessor directives Preprocessor directives Comments Comments

Parm

Embed Size (px)

DESCRIPTION

inrductin about discovery of c++

Citation preview

Page 1: Parm

January 26, 2012 CS410 – Software Engineering Lecture #2: Hello, C++ World!

1

C++ OverviewC++ Overview

• History and major features of C++History and major features of C++• Input and outputInput and output• Preprocessor directivesPreprocessor directives• CommentsComments

Page 2: Parm

History of C++History of C++

1972: C language developed at Bell Labs1972: C language developed at Bell Labs•Dennis Ritchie wrote C for Unix OSDennis Ritchie wrote C for Unix OS•Needed C for work with UnixNeeded C for work with Unix

late 70s: C becomes popular for OS development by late 70s: C becomes popular for OS development by many vendorsmany vendors•Many variants of the language developedMany variants of the language developed•ANSI standard C in 1987-89ANSI standard C in 1987-89

Page 3: Parm

History of C++ (continued)History of C++ (continued)

early 80s: Bjarne Stroustrup adds early 80s: Bjarne Stroustrup adds OOOO features to C features to C creating C++creating C++

90s: continued evolution of the language and its 90s: continued evolution of the language and its applicationsapplications•preferred language for OS and low level preferred language for OS and low level

programmingprogramming•popular language for application developmentpopular language for application development•low level control and high level powerlow level control and high level power

Page 4: Parm

January 26, 2012 CS410 – Software Engineering Lecture #2: Hello, C++ World!

4

History of C++History of C++• 1980: “C-with-classes” developed by Bjarne Stroustrup1980: “C-with-classes” developed by Bjarne Stroustrup

• 1983: C-with-classes redesigned and called C++1983: C-with-classes redesigned and called C++

• 1985: C++ compilers made available1985: C++ compilers made available

• 1989: ANSI/ISO C++ standardization starts1989: ANSI/ISO C++ standardization starts

• 1998: ANSI/ISO C++ standard approved1998: ANSI/ISO C++ standard approved

Page 5: Parm

Conceptually what is C++Conceptually what is C++

Alternatives:Alternatives:•is it C, with lots more options and features?is it C, with lots more options and features?•is it an OO programming language with C as is it an OO programming language with C as

its core?its core?•is it a development environment?is it a development environment?

On most systems it is a development environment, On most systems it is a development environment, language, and library, used for both procedural language, and library, used for both procedural and object oriented programming, that can be and object oriented programming, that can be customized and extended as desiredcustomized and extended as desired

Page 6: Parm

Versions of C++Versions of C++

ANSI C++ANSI C++Microsoft C++ (MS Visual C++ 6.0)Microsoft C++ (MS Visual C++ 6.0)Other vendors: Borland, Symantec, Turbo, …Other vendors: Borland, Symantec, Turbo, …Many older versions (almost annual) including Many older versions (almost annual) including

different version of C toodifferent version of C tooMany vendor specific versionsMany vendor specific versionsMany platform specific versionsMany platform specific versionsFor this class: Unix / Linux based versionsFor this class: Unix / Linux based versions

•g++g++

Page 7: Parm

Characteristics of C++ as a Computer Characteristics of C++ as a Computer LanguageLanguage

ProceduralProcedural

Object OrientedObject Oriented

ExtensibleExtensible

......

Page 8: Parm

Other OO LanguagesOther OO Languages

SmalltalkSmalltalk•pure OO language developed at PARCpure OO language developed at PARC

Java Java •built on C/C++built on C/C++•objects and data typesobjects and data types

Eifel and othersEifel and others

Page 9: Parm

What you can do with C++What you can do with C++

Apps (standalone, Web apps, components)Apps (standalone, Web apps, components)

Active desktop (Dynamic HTML, incl Web)Active desktop (Dynamic HTML, incl Web)

Create graphical appsCreate graphical apps

Data access (e-mail, files, ODBC)Data access (e-mail, files, ODBC)

Integrate components w/ other languagesIntegrate components w/ other languages

Page 10: Parm

January 26, 2012 CS410 – Software Engineering Lecture #2: Hello, C++ World!

10

Major Features of C++Major Features of C++• Almost upward compatible with CAlmost upward compatible with C

• Not Not allall valid C programs are valid C++ valid C programs are valid C++ programs.programs.

• Why?Why?• Because of reserved words in C++ such as Because of reserved words in C++ such as

‘class’‘class’• Extends C with object-oriented featuresExtends C with object-oriented features

• Compile-time checking: strongly typedCompile-time checking: strongly typed

• Classes with multiple inheritanceClasses with multiple inheritance

• No garbage collection, but semi-automatic No garbage collection, but semi-automatic storage reclamationstorage reclamation

Page 11: Parm

Disadvantages of C++Disadvantages of C++

Tends to be one of the less portable languagesTends to be one of the less portable languages

Complicated? Complicated? •40 operators, intricate precedence, pointers, etc.40 operators, intricate precedence, pointers, etc.•can control everythingcan control everything•many exceptions and special casesmany exceptions and special cases•tremendous libraries both standard, vendor tremendous libraries both standard, vendor

specific, and available for purchase, but all are specific, and available for purchase, but all are intricateintricate

Aspects above can result in high maintenance costsAspects above can result in high maintenance costs

Page 12: Parm

Advantages of C++Advantages of C++

Available on most machinesAvailable on most machines

Can get good performanceCan get good performance

Can get small sizeCan get small size

Can manage memory effectivelyCan manage memory effectively

Can control everythingCan control everything

Good supply of programmersGood supply of programmers

Suitable for almost any type of program (from Suitable for almost any type of program (from systems programs to applications)systems programs to applications)

Page 13: Parm

January 26, 2012 CS410 – Software Engineering Lecture #2: Hello, C++ World!

13

Sample C++ ProgramSample C++ Program#include <iostream>#include <iostream>#include <string>#include <string>using namespace std;using namespace std;

int main()int main(){{ string deptChairName, deptChairPasswd, string deptChairName, deptChairPasswd,

enteredPasswd;enteredPasswd; bool passwdOK;bool passwdOK; int attempts = 0;int attempts = 0;

deptChairName = GetDeptChairName();deptChairName = GetDeptChairName(); deptChairPasswd = GetDeptChairPasswd();deptChairPasswd = GetDeptChairPasswd();

cout << "How are you today, " << cout << "How are you today, " << deptChairName << "?\n";deptChairName << "?\n";

do do {{ cout << "Please enter your password: ";cout << "Please enter your password: "; cin >> enteredPasswd;cin >> enteredPasswd; attempts++;attempts++;

if (enteredPasswd == deptChairPasswd)if (enteredPasswd == deptChairPasswd) {{ cout << "Thank you!" << endl;cout << "Thank you!" << endl; passwdOK = true;passwdOK = true; }} elseelse {{ cout << "Hey! Are you really " << cout << "Hey! Are you really " <<

deptChairName << "?\n"; deptChairName << "?\n"; cout << "Try again!\n";cout << "Try again!\n"; passwdOK = false;passwdOK = false; }} }} while (!passwdOK && attempts < 3);while (!passwdOK && attempts < 3); if (passwdOK)if (passwdOK) SetNewParameters();SetNewParameters(); elseelse {{ Shout(“Warning! Illegal access!”);Shout(“Warning! Illegal access!”); CallCampusPolice();CallCampusPolice(); }} return 0;return 0;}}

Page 14: Parm

January 26, 2012 CS410 – Software Engineering Lecture #2: Hello, C++ World!

14

Input and OutputInput and Output

• Some standard functions for input and output are Some standard functions for input and output are provided by the provided by the iostream libraryiostream library..

• The iostream library is part of the The iostream library is part of the standard librarystandard library..• Input from the terminal (Input from the terminal (standard inputstandard input) is tied to ) is tied to

the iostream object the iostream object cincin..• Output to the terminal (Output to the terminal (standard outputstandard output) is tied to ) is tied to

the iostream object the iostream object coutcout..• Error and warning messages can be sent to the user Error and warning messages can be sent to the user

via the iostream object via the iostream object cerrcerr ( (standard errorstandard error).).

Page 15: Parm

January 26, 2012 CS410 – Software Engineering Lecture #2: Hello, C++ World!

15

Input and OutputInput and Output

• Use the output operator (Use the output operator (<<<<) to direct a value to ) to direct a value to standard output.standard output.

• Successive use of << allows concatenation.Successive use of << allows concatenation.• Examples:Examples:

•cout << “Hi there!\n”; cout << “Hi there!\n”; •cout << “I have “ << 3 + 5 << “ classes today.”;cout << “I have “ << 3 + 5 << “ classes today.”;•cout << “goodbye!” << endl; cout << “goodbye!” << endl; (new line & flush)(new line & flush)

Page 16: Parm

January 26, 2012 CS410 – Software Engineering Lecture #2: Hello, C++ World!

16

Input and OutputInput and Output

• Use the input operator (Use the input operator (>>>>) to read a value from ) to read a value from standard input.standard input.

• Standard input is read word by word (words are Standard input is read word by word (words are separated by spaces, tabs, or newlines).separated by spaces, tabs, or newlines).

• Successive use of >> allows reading multiple words Successive use of >> allows reading multiple words into separate variables.into separate variables.

• Examples:Examples:•cin >> name;cin >> name;•cin >> nameA >> nameB;cin >> nameA >> nameB;

Page 17: Parm

January 26, 2012 CS410 – Software Engineering Lecture #2: Hello, C++ World!

17

Input and OutputInput and Output

How can we read an unknown number of input How can we read an unknown number of input values?values?

int main()int main()

{{

string word;string word;

while (cin >> word)while (cin >> word) cout << “word read is: “ << word << “\n”; cout << “word read is: “ << word << “\n”;

cout << “OK, that’s all.\n”;cout << “OK, that’s all.\n”;

return 0;return 0;}}

Page 18: Parm

January 26, 2012 CS410 – Software Engineering Lecture #2: Hello, C++ World!

18

Input and OutputInput and Output

The previous program will work well if we use a file The previous program will work well if we use a file instread of the console (keyboard) as standard input.instread of the console (keyboard) as standard input.

In Linux, we can do this using the “<“ symbol.In Linux, we can do this using the “<“ symbol.

Let us say that we have created a text file “input.txt” Let us say that we have created a text file “input.txt” (e.g., by using gedit) in the current directory.(e.g., by using gedit) in the current directory.

It contains the following text:It contains the following text:“This is just a stupid test.”“This is just a stupid test.”

Let us further say that we stored our program in a file Let us further say that we stored our program in a file named “test.C” in the same directory.named “test.C” in the same directory.

Page 19: Parm

January 26, 2012 CS410 – Software Engineering Lecture #2: Hello, C++ World!

19

Input and OutputInput and Output

We can now compile our program using the g++ We can now compile our program using the g++ compiler into an executable file named “test”:compiler into an executable file named “test”:

$ g++ test.C –o test$ g++ test.C –o test

The generated code can be executed using the The generated code can be executed using the following command:following command:

$ ./test$ ./test

If we would like to use the content of our file “input.txt” If we would like to use the content of our file “input.txt” as standard input for this program, we can type the as standard input for this program, we can type the following command:following command:

$ ./test < input.txt$ ./test < input.txt

Page 20: Parm

January 26, 2012 CS410 – Software Engineering Lecture #2: Hello, C++ World!

20

Input and OutputInput and Output

We will then see the following output in our terminal:We will then see the following output in our terminal:

Word read is: ThisWord read is: ThisWord read is: isWord read is: isWord read is: justWord read is: justWord read is: aWord read is: aWord read is: stupidWord read is: stupidWord read is: test.Word read is: test.OK, that’s all.OK, that’s all.

Page 21: Parm

January 26, 2012 CS410 – Software Engineering Lecture #2: Hello, C++ World!

21

Input and OutputInput and OutputIf we want to redirect the standard output to a file, say If we want to redirect the standard output to a file, say “output.txt”, we can use the “>” symbol:“output.txt”, we can use the “>” symbol:

$ ./test < input.txt > output.txt$ ./test < input.txt > output.txtWe can read the contents of the generated file by We can read the contents of the generated file by simply typing:simply typing:

$ less output.txt$ less output.txt

We will then see that the file contains the output that We will then see that the file contains the output that we previously saw printed in the terminal window.we previously saw printed in the terminal window.

(By the way, press “Q” to get the prompt back.)(By the way, press “Q” to get the prompt back.)

Page 22: Parm

January 26, 2012 CS410 – Software Engineering Lecture #2: Hello, C++ World!

22

Input and OutputInput and OutputIf you use keyboard input for your program, it will If you use keyboard input for your program, it will never terminate but instead wait for additional input.never terminate but instead wait for additional input.

Use the Use the getlinegetline command to read an entire line from command to read an entire line from cincin, and put it into a , and put it into a stringstreamstringstream object that can be object that can be read word by word just like read word by word just like cincin..

Using stringstream objects requires the inclusion of Using stringstream objects requires the inclusion of the sstream header file:the sstream header file:

#include <sstream>#include <sstream>

Page 23: Parm

January 26, 2012 CS410 – Software Engineering Lecture #2: Hello, C++ World!

23

Input and OutputInput and Output#include <iostream>#include <iostream>#include <sstream>#include <sstream>#include <string>#include <string>using namespace std;using namespace std;

int main()int main(){{ string userinput, word; string userinput, word; getline(cin, userinput); getline(cin, userinput);

stringstream mystream(userinput);stringstream mystream(userinput);

while (mystream >> word)while (mystream >> word)

cout << "word read is: " << word << "\n";cout << "word read is: " << word << "\n";

cout << "OK, that’s all.\n";cout << "OK, that’s all.\n";

return 0;return 0;

}}

Page 24: Parm

January 26, 2012 CS410 – Software Engineering Lecture #2: Hello, C++ World!

24

Input and OutputInput and OutputBy the way, you are not limited to strings when using By the way, you are not limited to strings when using cincin and and coutcout, but you can use other types such as , but you can use other types such as integers.integers.

However, if your program expects to read an integer However, if your program expects to read an integer and receives a string, the read operation will fail.and receives a string, the read operation will fail.

If your program always uses file input and output, it is If your program always uses file input and output, it is better to use better to use fstreamfstream objects instead of objects instead of cincin and and coutcout..

Page 25: Parm

January 26, 2012 CS410 – Software Engineering Lecture #2: Hello, C++ World!

25

File Input and OutputFile Input and Output#include <iostream>#include <iostream>#include <fstream>#include <fstream>#include <string>#include <string>using namespace std;using namespace std;

int main()int main(){{ ofstream outfile(“out_file.txt”);ofstream outfile(“out_file.txt”); ifstream infile(“in_file.txt”);ifstream infile(“in_file.txt”);

if (!infile)if (!infile) {{ cerr << “error: unable to open cerr << “error: unable to open input file”; input file”; return –1;return –1; }}

if (!outfile)if (!outfile) {{ cerr << “error: unable to open cerr << “error: unable to open

output file”; output file”; return –2;return –2; }}

string word;string word; while (infile >> word)while (infile >> word) outfile << word << “_”;outfile << word << “_”;

return 0;return 0;}}

Page 26: Parm

January 26, 2012 CS410 – Software Engineering Lecture #2: Hello, C++ World!

26

Preprocessor DirectivesPreprocessor Directives

Preprocessor directivesPreprocessor directives are specified by placing a are specified by placing a pound sign (pound sign (##) in the very first column of a line in our ) in the very first column of a line in our program.program.

For example, header files are made part of our For example, header files are made part of our program by the preprocessor program by the preprocessor include directiveinclude directive..

The preprocessor replaces the #include directive with The preprocessor replaces the #include directive with the contents of the named file.the contents of the named file.

There are two possible forms:There are two possible forms:

#include <standard_file.h>#include <standard_file.h>

#include “my_file.h”#include “my_file.h”

Page 27: Parm

January 26, 2012 CS410 – Software Engineering Lecture #2: Hello, C++ World!

27

Preprocessor DirectivesPreprocessor Directives

If the file name is enclosed in If the file name is enclosed in angle bracketsangle brackets (<, >), (<, >), the file is presumed to be a the file is presumed to be a standard header filestandard header file..

Therefore, the preprocessor will search for the file in Therefore, the preprocessor will search for the file in a a predefined set of locationspredefined set of locations..

If the file name is enclosed by a pair of If the file name is enclosed by a pair of quotation quotation marksmarks, the file is presumed to be a , the file is presumed to be a user-supplied user-supplied header fileheader file..

Therefore, the search for the file begins in the Therefore, the search for the file begins in the directory in which the including file is located (directory in which the including file is located (project project directorydirectory).).

Page 28: Parm

January 26, 2012 CS410 – Software Engineering Lecture #2: Hello, C++ World!

28

Preprocessor DirectivesPreprocessor Directives

The included file may itself contain an #include The included file may itself contain an #include directive (directive (nestingnesting).).This can lead to the same header file being included This can lead to the same header file being included multiple times in a single source file.multiple times in a single source file.Conditional directivesConditional directives guard against the multiple guard against the multiple processing of a header file.processing of a header file.

Example:Example:#ifndef SHOUT_H#ifndef SHOUT_H#define SHOUT_H#define SHOUT_H /* shout.h definitions go here *//* shout.h definitions go here */#endif#endif

Page 29: Parm

January 26, 2012 CS410 – Software Engineering Lecture #2: Hello, C++ World!

29

Preprocessor DirectivesPreprocessor Directives

The The #ifdef, #ifndef#ifdef, #ifndef, and , and #endif#endif directives are most directives are most frequently used to conditionally include program code frequently used to conditionally include program code depending on whether a preprocessor constant is depending on whether a preprocessor constant is defined.defined.

This can be useful, for example, for This can be useful, for example, for debuggingdebugging::

Page 30: Parm

January 26, 2012 CS410 – Software Engineering Lecture #2: Hello, C++ World!

30

Preprocessor DirectivesPreprocessor Directives

int main()int main(){{

#ifdef DEBUG#ifdef DEBUG cout << “Beginning execution of main()\n”;cout << “Beginning execution of main()\n”;#endif#endif

string word;string word; while (cin >> word)while (cin >> word) cout << “word read is: “ << word << “\n”; cout << “word read is: “ << word << “\n”; cout << “OK, that’s all.”;cout << “OK, that’s all.”; return 0;return 0;}}

Page 31: Parm

January 26, 2012 CS410 – Software Engineering Lecture #2: Hello, C++ World!

31

CommentsComments

• Comments are an important aid to human readers Comments are an important aid to human readers of our programs.of our programs.

• Comments need to be updated as the software Comments need to be updated as the software develops.develops.

• Do not obscure your code by mixing it with too Do not obscure your code by mixing it with too many comments.many comments.

• Place a comment block above the code that it is Place a comment block above the code that it is explaining.explaining.

• Comments do not increase the size of the Comments do not increase the size of the executable file.executable file.

Page 32: Parm

January 26, 2012 CS410 – Software Engineering Lecture #2: Hello, C++ World!

32

CommentsCommentsIn C++, there are two different comment delimiters:In C++, there are two different comment delimiters:• the the comment paircomment pair (/*, */), (/*, */),• the the double slashdouble slash (//). (//).

The comment pair is identical to the one used in C:The comment pair is identical to the one used in C:• The sequence /* indicates the beginning of a The sequence /* indicates the beginning of a

comment.comment.• The compiler treats all text between a /* and the The compiler treats all text between a /* and the

following */ as a comment.following */ as a comment.• A comment pair can be multiple lines long and can A comment pair can be multiple lines long and can

be placed wherever a tab, space, or newline is be placed wherever a tab, space, or newline is permitted.permitted.

• Comment pairs Comment pairs do not nestdo not nest..

Page 33: Parm

January 26, 2012 CS410 – Software Engineering Lecture #2: Hello, C++ World!

33

CommentsComments

The The double slashdouble slash serves to delimit a single-line serves to delimit a single-line comment:comment:• Everything on the program line to the right of the Everything on the program line to the right of the delimiter is treated as a comment and ignored by delimiter is treated as a comment and ignored by the compiler. the compiler.

A typical program contains A typical program contains both typesboth types of comments. of comments.

In general, use comment pairs to explain the In general, use comment pairs to explain the capabilities of a class and the double slash to explain capabilities of a class and the double slash to explain a single operation.a single operation.