65
The first part is presented out-of-sequence, at the end of lecture 2 from ch.1.

The first part is presented out-of-sequence, at the end of ... first C++ program This is a C string (terminated with an implicit null character!), but in C++ we shall call it a “character

  • Upload
    buingoc

  • View
    216

  • Download
    1

Embed Size (px)

Citation preview

The first part is presented out-of-sequence, at the end of lecture 2 from ch.1.

Ch. 2: Making and Using Objects

Your first C++ program

Your first C++ program

This is a C string (terminated with an

implicit null character!), but in C++ we shall call it

a “character array” to distinguish it from the C++ library class string.

Character combination used by the author in

comments (not standard!)

Accepts data and sends it

to the standard output

(usually the console window)

Defines the object cout

Namespaces

One of the problems encountered in the C language is that you “run out of names” for functions and identifiers when your programs reach a certain size.

Of course, you don’t really run out of names; it does, however, become harder to think of new ones in large programs.

More importantly, when a program reaches a certain size it’s typically broken up into pieces, each of which is built and maintained by a different person or group.

Since C effectively has a single arena where all the identifier and function names live, this means that all the developers must be careful not to accidentally use the same names in situations where they can conflict.

This rapidly becomes tedious, time-wasting, and, ultimately, expensive.

Standard C++ has a mechanism to prevent this collision: the namespace keyword. Each set of C++ definitions in a library or program is “wrapped” in a namespace, and if some other definition has an identical name, but is in a different namespace, then there is no collision.

There’s a keyword that allows you to say “I want to use the declarations and/or definitions in this namespace.” This keyword, appropriately enough, is using. All of the Standard C++ libraries are wrapped in a single namespace, which is std (for “standard”):

If we decide not to expose the entire namespace, any class/object from that namespace has to be prefaced by its name, like so:

std::

std::

Another example: string is the C++

replacement for C’s array of characters.

Exposing all the elements from a namespace after someone has gone to the trouble to hide them may seem a bit counterproductive, and in fact you should be careful about doing this […].

However, the using directive exposes only those names for the current file, so it is not quite as drastic as it first sounds. (But think twice about doing it in a header file –that is reckless.)

Running the compiler

Ignore this sub-section, as it applies only when we compile from the commands line.

In the MSVS IDE, we use CTRL+F5 instead (Run Without Debugging).

QUIZ

Write a complete C++ program to display COSC 2321 on the screen without exposing the namespace std.

Solution

Write a complete C++ program to display COSC 2321 on the screen without exposing the namespace std.

EOL 0

Solution

1. Write a complete C++ program to display COSC 2321 on the screen, exposing the namespace std.

This comes at the end of Lecture 3 from Ch.1

QUIZ

2. What are the pros and cons of using

in a C++ program?

The process of language translation

Interpreter vs. compiler

• Why interpreters are slow:

– Each line of the program is translated as it is reached in the flow of execution, and then discarded

– If a loop executes 1M times, its body is translated 1M times!

– Interpreter has to determine the type of each variable each time it encounters it!

The process of language translation

Interpreter vs. compiler

• Then why use interpreters?

It’s easier to interact with the program, which leads to faster development.

The process of language translation

Interpreter vs. compiler

• Compiler advantages:

– Programs translated by compiler need less memory space to run

– They also run faster

– Independent compilation is possible → modularity

– The object files created by separate compilation are eventually combined by the linker

Image source: http://www.cs.miami.edu/home/geoff/Courses/CSC322-11S/Content/CTools/Make.shtml

One (and only one) source file must contain the main() function.

Runtime environment

The compilation process

Source code

Preprocessor

Compiler pass 1 = parser

Global optimizer

Compiler pass 2 = code generation

Peephole optimizer

Object file

This “object” has nothing to do with OOP!

Example of tree generated by a parser

Global optimization example: unrolling a loop

Source: https://en.wikipedia.org/wiki/Loop_unrolling#A_simple_manual_example_in_C

• The test x < 100 is performed only 20 times instead of 100.• Due to the reduced nr. of branching instructions in the assembly /

machine code, the CPU pipeline stays full longer.

Linking example: system call

EOL 1

QUIZ

1. What are the 2 main options we have in C/C++ with respect to the lifetime of variables and objects?

2. What memory areas are used to implement the options above?

Solution

1. What are the 2 main options we have in C/C++ with respect to the lifetime of variables and objects?

2. What memory areas are used to implement the options above?

A. Declared (a.k.a. scoped or automatic) variables, whose lifetime (creation and destruction) is under the control of the compiler.

B. Dynamically-allocated variables, whose lifetime is under the control of the programmer (malloc/new and free/delete).

A. Stack + Static storageB. Heap

QUIZ

3. Why is code reuse important when developing software?

4. What are the two techniques for reusing code in OOP?

5. Show an example UML diagram for each of the above.

6. What does the acronym UML stand for?

QUIZ

7. What are the steps in the translation of a C/C++ program?

Solution

7. What are the steps in the translation of a C/C++ program?

Type checking

In C and C++, type checking (TC) is normally performed during the first pass of compilation → Static TC.

But dynamic TC support is also provided to “navigate” object hierarchies (see Ch.15)

• Similar to late binding – it is done at runtime!

• We call it dynamic TC.

This has nothing to do with the static storage specifier!

Tools for separate compilation

“ […] the function is the atomic unit of code, since you cannot have part of a function in one file and another part in a different file; the entire function must be placed in a single file (although files can and do contain more than one function).”

Tools for separate compilation

“To create a program with multiple files, functions in one file must access functions and data in other files. When compiling a file, the C or C++ compiler must know about the functions and data in the other files, in particular their names and proper usage. […]

This process of “telling the compiler” the names of external functions and data and what they should look like is called declaration.”

Declarations vs. definitions

A declaration introduces a name – an identifier –to the compiler. It tells the compiler “This function or this variable exists somewhere, and here is what it should look like.”

A definition, on the other hand, says: “Make this variable here” or “Make this function here.” It allocates storage for the name.

Declarations vs. definitions

“You can declare a variable or a function in many different places, but there must be only one definition in C and C++ (this is sometimes called the ODR: one-definition rule).

When the linker is uniting all the object modules, it will usually complain if it finds more than one definition for the same function or variable.”

Declarations vs. definitions

A definition can also be a declaration.

If the compiler hasn’t seen the name x before and you define

int x;

the compiler sees the name as a declaration and allocates storage for it all at once.

Declarations vs. definitions

This, however, is just a declaration:

extern int x;

Function declaration syntax

The compiler ignores the names of the arguments in the declaration (but they can be helpful as mnemonic devices for the user).

Function declaration orfunction prototype?

At the beginning of Ch.3, the author splits hairs:

“ […] the form of function declaration in C++ requires proper prototyping.”

Dr. Agapie says: Use them interchangeably!

Function definition syntax

//code here

QUIZ

Write the declaration/prototype of a function sumthat takes two integer arguments in the range 10-40,000, and returns their sum.

Hint: Think about the data types involved!

Then write the function definition.

Solution

unsigned int sum(unsigned short, unsigned short);

optional

A difference between declaring variables and functions

Variables don’t have bodies {} like functions, and ambiguity arises → solved with the keyword extern:

declaration

definition

A difference between declaring variables and functions

a.k.a. prototypes

QUIZWrite:

• The declaration of a double variable foo.

• The definition of the variable foo above.

• The initialization of the variable foo above.

• The declaration/prototype of a double function bar with one float argument.

– The function simply converts the argument to double and returns it.

• The definition of the function bar.

• A call to the function bar.

Solution

extern double foo;

double foo;

foo = 1.5;

double bar(float);

double bar(float x){return (double)x;}

y = bar(1.5f);

Name of argument is optional

Extern is optional

Name of argument is not optional

C-style typecasting

Standard C++ include format

Standard C++ include format

The effect of the new include format is not identical to the old: using the .h gives you the older, non-template version, and omitting the .hgives you the new templatized version. You’ll usually have problems if you try to intermix the two forms in a single program.

Can I write #include <iostream.h> ?

Source: http://stackoverflow.com/questions/13820285/location-of-iostream-h-in-gcc EOL 2

QUIZ

1. Explain in your own words the concepts of declaring and defining (variables or functions).

2. How is declaring a function different from declaring a variable? (Think of the keyword extern)

3. What is the meaning of a function with an empty list of arguments:• In C?

• In C++

QUIZ

4. Which are correct function declarations in C/C++?

a. int foo(int, int, int);

b. int foo(int a, int b, int c);

c. int foo(int a, int b, int c){ return a+b-c; }

d. int foo(int a, b, c);

e. extern int foo(int, int, int);

More about iostreams

Fixed-precision floating point is default

No, there is no manipulator for binary!

In more depth:sticky vs. non-sticky settings

Not in text

The setw manipulatorNot in text

Unlike the previous manipulators, setw is

defined in the iomanipheader.

Also “non-sticky” (must be repeated)!

The cout.width method is not sticky

Needs to be reasserted

before each cout, i.e.

“non-sticky”!

Stays active until changed by

another manipulator, i.e.

it’s “sticky”!

Yes, this is allowed in

C++!

Not in text

cout.precision(8);

cout <<setprecision(8) <<...

ConclusionNot in text

The manipulator setw and the method width• have the same functionality• are the only two non-sticky controls

For more details on I/O formatting (justification, precision, filling) try this resource:http://www.stormingrobots.com/prod/tutorial/streamIOBasic.pdf

Reading input

Stream insertion operator

Stream extraction operator

Introducing strings

Reading and writing files

Compare the C++ version of getline with the C version – what do you notice? Explain!

Introducing vector

This is a template, used for generic programming!

Introducing vector

The opposite method,

pop_back() is not

mentioned in Ch.2, but it will prove useful in applications.

Dynamic arrays, VLAs, C99

Variable Length Arrays (VLAs) were introduced in C99, but made optional in C11!

Source: https://msdn.microsoft.com/en-us/library/zb1574zs.aspx

… but the GCC compiler does support them!

Historical note (not in text)

Homework for chs. 1 & 2

Provided as separate handout (also available on our webpage --> agapie.net)

Due Monday, Feb.5, at the beginning of class.

Please hand in a hard-copy, do not email!

EOL 3