C++ Programming for CE
PD Dr. Harald Köstler
15.10.2015
Lecture 1
2
Organization and Motivation
3
Educational Goals
Understand C++ concepts, object-oriented, and
generic programming
Be able to do modular and efficient implementations of
algorithms in C++
Structure your software
What do you expect from the lecture?
4
Lecture
Based on C++
Less slides, more code discussions
Bring your laptop and work alone or in pairs
Ask and give feedback
Register via mycampus until 31.10.2015
Schedule
Thursday 8:30-10:00, H5
5
Exercise
Responsible: A. Ditter
Exercise sheets are found in Studon
Schedule
Monday 10:15-11:45, 16:00-17:30, 01.155-113 (starts on 19.10.!)
6
Organization
You may use all operating systems (Linux, Mac OS,
Windows)
Compilers, e.g. g++ or cl (Visual Studio)
Learn to program platform independent!
Prepare simple main program for small tests
Why C++?
Object-oriented language
Supports most programming paradigms
Used by many researchers and companies
suitable for HPC (?!)
7
Contents
1. Introduction to C++
● Variables and Types
● Expressions and Statements
● Functions
● Classes
2. Introduction to the C++ standard library
● IO library
● Sequential containers
● Generic Algorithms
● Associative Containers
● Dynamic memory
3. Advanced Topics
● OOP
● Templates
8
Exam
Categories:
Reproduce and explain terms in C++ and OO
Explain syntax and semantic of C++ programs
Find errors in code fragments and correct them
Write own classes and functions
Map problems to classes and algorithms
9
Literature
S. Lippman et al, C++ Primer, 5th edition. Addison
Wesley, 2012 (www.awprofessional.com/cpp_primer)
http://www.informit.com/store/c-plus-plus-primer-
9780321714114
And many more
10
Programming Language Features I
Essentially all programming languages provide:
Built-in data types (integers, characters, …)
Expressions and statements to manipulate values of
these types
Variables to name the objects we use
Control structures (if, while, …) to conditionally
execute or repeat a set of actions
Functions to abstract actions into callable units of
computation
But Programming languages also have distinctive
features that determine the kinds of applications for which
they are well suited
11
Programming Language Features II
Most modern programming languages
supplement this basic set of features in two ways:
they let programmers extend the language by defining
their own data types
they provide a set of library routines that define useful
functions and data types not otherwise built into the
language.
12
Introduction to C++
13
C++ Keywords
79
http://en.cppreference.com/w/cpp/keyword
The first C++ program
int main() {
return 0;
}
Terms:
statement, block, curly brace
function, function name, parameter list, function body
return type, argument
Questions:
How to compile and run program in Linux/Windows?
15
Definitions
statement: Smallest independent unit in a C++ program,
analogous to a sentence in a natural language. Ends in
semicolon!
block: Sequence of statements enclosed in curly braces
curly brace: Curly braces delimit blocks.
16
Definitions
function: A named unit of computation.
main function: Function called by the operating system
when executing a C++ program. Each program must have
one and only one function named main.
function body: Statement block that defines the actions
performed by a function.
function name: Name by which a function is known and
can be called.
17
Definitions
return type: Type of the value returned by a function.
parameter list: Part of the definition of a function.
Possibly empty list that specifies what arguments can be
used to call the function.
argument: A value passed to a function when it is called.
18
Standard IO
#include <iostream>
int main()
{
std::cout << "Enter two numbers:" << std::endl;
int i, j; // not initialized, because read by cin
std::cin >> i >> j;
std::cout << "The sum of " << i << " and " << j
<< " is " << i + j << std::endl;
return 0;
}
Terms:
variable, built-in type, expression, comment
standard library and IO, header, preprocessor directive
input/output operator, namespace, scope operator
Questions:
What means flushing a buffer? Why do so?
When to initialize variables?
19
Definitions
variable: A named object.
built-in type: A type, such as int, defined by the language.
uninitialized variable: Variable that has no initial value
specified. Uninitialized variables are a rich source of bugs.
20
Definitions
comments: Program text ignored by the compiler: single-
line (//) and paired (/* … */)
Expression: Smallest unit of computation.
An expression consists of one or more operands and
usually an operator. Expressions are evaluated to produce
a result.
For example, assuming i and j are ints, then i + j is an
arithmetic addition expression and yields the sum of the
two int values.
21
Definitions
header: A mechanism whereby the definitions of a class or
other names may be made available to multiple programs.
A header is included in a program through a #include directive.
preprocessor directive: An instruction to the C++
preprocessor. #include is a preprocessor directive. Preprocessor
directives must appear on a single line.
source file: Term used to describe a file that contains a C++
program.
22
Definitions
standard library: Collection of types and functions that
every C++ compiler must support. The library provides a
rich set of capabilities including the types that support IO.
iostream: Library type providing stream-oriented input
and output (also istream, ostream).
library type: A type, such as istream, defined by the
standard library.
23
Definitions
standard input: The input stream that ordinarily is
associated by the operating system with the window in
which the program executes.
cin: istream object used to read from the standard input.
24
Definitions
standard output: The output stream that ordinarily is
associated by the operating system with the window in
which the program executes.
cout: ostream object used to write to the standard output.
Ordinarily used to write the output of a program.
25
Definitions
standard error: An output stream intended for use for
error reporting.
cerr: ostream object tied to the standard error, which is
often the same stream as the standard output. By default,
writes to cerr are not buffered.
clog: ostream object tied to the standard error. By default,
writes to clog are buffered. Usually used to report
information about program execution to a log file
26
Definitions
<< operator: Output operator. Writes the right-hand
operand to the output stream indicated by the left-hand
operand:
cout << "hi" writes hi to the standard output.
>> operator: Input operator. Reads from the input
stream specified by the left-hand operand into the right-
hand operand:
cin >> i reads the next value on the standard input to i.
27
Definitions
Buffer: A region of storage used to hold data. IO
facilities often store input (or output) in a buffer and read
or write the buffer independently of actions in the
program.
Output buffers usually must be explicitly flushed to force
the buffer to be written. By default, reading cin flushes
cout; cout is also flushed when the program ends
normally.
manipulator: Object, such as std::endl, that when read
or written "manipulates" the stream itself.
28
Definitions
namespace: Mechanism for putting names defined by a
library into a single place. Namespaces help avoid
inadvertent name clashes.
std: Name of the namespace used by the standard library.
std::cout indicates that we're using the name cout defined
in the std namespace.
:: operator: Scope operator. Among other uses, the scope
operator is used to access names in a namespace. For
example, std::cout says to use the name cout from the
namespace std.
29
While Statement I
#include <iostream>
int main()
{
int sum = 0, val = 1;
while (val <= 10) {
sum += val;
++val;
}
std::cout << "Sum of 1 to 10 inclusive is "
<< sum << std::endl;
return 0;
}
Terms:
condition
compound assignment operator, prefix increment
30
Definitions
while statement: An iterative control statement that
executes the statement that is the while body as long as a
specified condition is true.
condition: An expression that is evaluated as true or
false.
An arithmetic expression that evaluates to zero is false;
any other value yields true.
31
Definitions
++ operator: Increment operator.
Adds one to the operand; ++i is equivalent to i = i+ 1.
+= operator: A compound assignment operator.
Adds right-hand operand to the left and stores the result back
into the left-hand operand; a += b is equivalent to a =a + b.
= operator: Assigns the value of the right-hand operand to
the object denoted by the left-hand operand.
32
Definitions
< operator: The less-than operator.
Tests whether the left-hand operand is less than the right-
hand (<= operator , >= operator, > operator).
== operator: The equality operator.
Tests whether the left-hand operand is equal to the right-
hand.
!= operator: The inequality operator.
Tests whether the left-hand operand is not equal to the
right-hand.
33
Reading inputs
#include <iostream>
int main()
{
int sum = 0, value;
while (std::cin >> value)
sum += value;
std::cout << "Sum is: " << sum << std::endl;
return 0;
}
Questions:
How many inputs are read?
34
Definitions
end-of-file: System-specific marker in a file that indicates
that there is no more input in the file (CTRL + Z or +D).
string literal: Sequence of characters enclosed in double
quotes.
35
For and If Statement
int main()
{
std::cout << "Enter two numbers:" << std::endl;
int v1, v2;
std::cin >> v1 >> v2; // read input
int lower, upper;
if (v1 <= v2) {
lower = v1;
upper = v2;
} else {
lower = v2;
upper = v1;
}
int sum = 0;
for (int val = lower; val <= upper; ++val)
sum += val;
std::cout << "Sum of " << lower
<< " to " << upper
<< " inclusive is "
<< sum << std::endl;
return 0;
}
36
Definitions
for statement: Control statement that provides iterative
execution.
Often used to step through a data structure or to repeat a
calculation a fixed number of times.
if statement: Conditional execution based on the value
of a specified condition.
If the condition is true, the if body is executed. If not,
control flows to the statement following the else.
37
Classes
#include <iostream>
#include "Sales_item.h"
int main()
{
Sales_item total, trans;
if (std::cin >> total) {
while (std::cin >> trans)
if (total.same_isbn(trans))
total = total + trans;
else {
std::cout << total << std::endl;
total = trans;
}
std::cout << total << std::endl;
} else {
std::cout << "No data?!" << std::endl;
return -1; // indicate failure
}
return 0;
}
Terms:
data structure, class, member functions / methods
dot operator
38
Definitions
class: C++ mechanism for defining our own data
structures. The class is one of the most fundamental
features in C++.
Library types, such as istream and ostream, are classes.
class type: A type defined by a class. The name of the type
is the class name.
data structure: A logical grouping of data and operations
on that data.
member function (method): Operation defined by a
class. Member functions ordinarily are called to operate on
a specific object.
39
Definitions
() operator: The call operator: A pair of parentheses "()"
following a function name.
The operator causes a function to be invoked. Arguments
to the function may be passed inside the parentheses.
. operator: Dot operator.
Takes two operands: the left-hand operand is an object
and the right is the name of a member of that object. The
operator fetches that member from the named object.
40
Sales_item.h: class definition (expert)
#ifndef SALESITEM_H
#define SALESITEM_H
#include <iostream>
#include <string>
class Sales_item {
friend bool operator==(const Sales_item&, const Sales_item&);
public:
Sales_item(const std::string &book):
isbn(book), units_sold(0), revenue(0.0) { }
Sales_item(std::istream &is) { is >> *this; }
friend std::istream& operator>>(std::istream&, Sales_item&);
friend std::ostream& operator<<(std::ostream&, const Sales_item&);
Sales_item& operator+=(const Sales_item&);
double avg_price() const;
bool same_isbn(const Sales_item &rhs) const
{ return isbn == rhs.isbn; }
Sales_item(): units_sold(0), revenue(0.0) { }
private:
std::string isbn;
unsigned units_sold;
double revenue;
};
#endif
41
Sales_item.h: class implementation I
Sales_item operator+(const Sales_item&, const Sales_item&);
inline bool
operator==(const Sales_item &lhs, const Sales_item &rhs)
{
return lhs.units_sold == rhs.units_sold &&
lhs.revenue == rhs.revenue &&
lhs.same_isbn(rhs);
}
inline bool
operator!=(const Sales_item &lhs, const Sales_item &rhs)
{
return !(lhs == rhs); // != defined in terms of operator==
}
using std::istream; using std::ostream;
// assumes that both objects refer to the same isbn
inline
Sales_item& Sales_item::operator+=(const Sales_item& rhs)
{
units_sold += rhs.units_sold;
revenue += rhs.revenue;
return *this;
}
// assumes that both objects refer to the same isbn
inline
Sales_item
operator+(const Sales_item& lhs, const Sales_item& rhs)
{
Sales_item ret(lhs); // copy lhs into a local object that we'll return
ret += rhs; // add in the contents of rhs
return ret; // return ret by value
}
42
Sales_item.h: class implementation II
inline
istream&
operator>>(istream& in, Sales_item& s)
{
double price;
in >> s.isbn >> s.units_sold >> price;
if (in)
s.revenue = s.units_sold * price;
else
s = Sales_item(); // input failed: reset object to default state
return in;
}
inline
ostream&
operator<<(ostream& out, const Sales_item& s)
{
out << s.isbn << "\t" << s.units_sold << "\t"
<< s.revenue << "\t" << s.avg_price();
return out;
}
inline
double Sales_item::avg_price() const
{
if (units_sold)
return revenue/units_sold;
else
return 0;
}
43