Sei sulla pagina 1di 21

C++ Programming

TI00AA50
Lecture 1 - 10.09.2015

Jarkko.Vuori@metropolia.fi

Pterois volitans, efficient (it eats smaller fishes fast),


but extremely poisonous just like C++

Motivation

C++ is typically the language of choice for


large, high performance applications

entertainment software
video games
device drivers
operating systems
server side programming
embedded software
scientific computing

C++ is the best-performing language on the


market but it also required the most
extensive tuning efforts, many of which were
done at a level of sophistication that would
not be available to the average programmer
Robert Hundt: Loop Recognition in C++/Java/Go/Scala, 2011

C++ is one language among many, but its


unusual combination of strengths make it an
essential tool for the serious engineer.
Although you may take years to fully
understand some of its features, you can
benefit from its power immediately
Nathan C. Myers: C++ in the Real World: Advice from the Trenches,
Dr. Dobb's Journal, Fall 1997

TI00AA50/JV

General information

WinhaWille system is used to enroll the course

Practical aim of this course

Learning practical object orienting programming using C++ programming language

Official aims of this course

Youll get to the WinhaWille system from the Metropolia web pages (www.metropolia.fi)
The identification code of the course is TI00AA50
You need to enroll the course in order to get the course material from the Tuubi

Understanding principles of object oriented programming, and how to apply them when
designing and implementing programs
Differences to Java programming language are discussed (e.g. memory management,
pointers when using objects)

Intended Learning Outcomes (upon successful completion of the module):

Knowledge and Understanding

The student will be able to

Understand object oriented concept


Understand C/C++ and Java/C++ differences
Analyze existing C++ programs

Professional Skills

The student will be able to

Create complete C++ programs using templates (when appropriate)

TI00AA50/JV

General information

Prerequisites:

C programming language (mandatory)

Java programming language (recommended)

Algorithms and Data Structures course (recommended)

Visual Studio 2012/2013 environment (or Linux & gcc environment)

2 h lectures/ one week (27-1 times, 26 h together)


Lab. work 2 h / week (27-1 times, 26 h together)
Self study (42h)
Two simultaneous lab groups

Note that there is no exam at the end of the first period


If you dont pass the exam, you can attend a resit exam after the course exam. For the resit exam dates, look for the Tuubi-portals workspace
(Tuubi>For student>Important dates>re-examination dates>Technology (for Finnish:
Tuubi>Opiskelijoille>Aikataulut>Uusintakoepivt>Tekniikka, tytila TiVi Leppvaara: Opinto-ohjaus) folder Documents/4. UUSINTATENTIT for
the exact resit exam dates

You have to fill the request (resit envelope) 10 working days before the resit exam
You can go to two resit exams at maximum, e.g. you can try only two times to pass the exam (after the courses main exam)
This course belongs to the resit exam group A1

Supporting books (not mandatory):

Algorithms, ADT, trees, dynamic memory, recursion

Exam at the end of the course (2h)

Basic object oriented concepts

This course is located to period 1 and 2


The extent of the course is 5 op

Pointers, structures, prototypes, defined types

Lippman, Lajoie, Moo: C++ Primer, Addison-Wesley, 2012


Josuttis: The C++ Standard Library, Addison-Wesley, 2012

Optional books (not mandatory, but for those more interested in C++)

Stroustrup: The C++ Programming Language, Addison-Wesley, 2013


Meyers: Effective C++, Addison-Wesley, 2005

Very Good book about object concept in general (not mandatory)

Useful links

Koskimies: Oliokirja, Satku, 2000 (in Finnish)


Good teaching material: http://en.wikiversity.org/wiki/Introduction_to_C%2B%2B
C++ vs. C: http://www.icce.rug.nl/documents/cplusplus/
General C++ reference: http://www.cplusplus.com/reference/
STL reference: http://www.cppreference.com/wiki/stl/start
Very useful C++ style guide (Industrial Strength C++): http://www.sannabremo.se/nyquist/industrial/

All the course material (lecture slides, lab works, example program files, extra material) are available from the Tuubi (tube.metropolia.fi)

TI00AA50/JV

General information

We have 13 lab assignments

You get one credit point from one exercise

Some labs contain also optional additional exercises

In order to get additional credit points


Optional labs must be done without any help

You must complete the assignment in the lab hours

0.25 can be added to the credit point depending how


bad/good you have performed

If for some reason you could not complete the lab


assignment, you can show it in the next lab session (one
week later)
If you return lab late, you will get an exponentially decaying
grade, e.g. (1/2)n, where n is the delay in weeks (after the
one week period)
Optional labs cannot be returned late at all, sorry

The final grade of the course is

min(5, round((exam-8)/(10/3,5)+1 + 0.3(labs-13))),

Where exam is the points of the exam (minimum 8 is


needed to pass, 18 points is the maximum), and labs is the
credit points from the labs

TI00AA50/JV

[T]here are known knowns; there are things we know we know.


We also know there are known unknowns;
that is to say we know there are some things we do not know.
But there are also unknown unknowns
the ones we don't know we don't know.
Former United States Secretary of Defense Donald Rumsfeld

Timetable
Lecture

Topic

Intro, differences between C and C++

Introduction to the object oriented programming

Constructors and destructors

Operator overloading

String class

Static/dynamic arrays, static class members

Composition and association class relations

Basics of inheritance

More inheritance (late binding, virtual methods, polyformism)

10

Template functions and classes, intro to STL (vector, iterators)

11

Iterator adaptors, function objects, other STL containers

12

Exceptions

13

C++ and C++11 smart pointers, right value references, move semantics

TI00AA50/JV

What is ++ in C?

C language is included in C++


(almost)
C++ contains additional tools for the
management of complexity
The most important tool of these is the
class, that makes object based and
object oriented programming possible
There are many other smaller
improvements in C++
All of these new features support in a
way the management of the
complexity:

e.g. void f();

C++

Function overloading
Operator overloading
Default parameters
Reference parameters
Inline-functions
Etc.

TI00AA50/JV

Function prototype f()


There are some differences in function declarations between C and C++

C-language
Function prototype void f();
Nothing is determined about parameters
So you can call it for example in the
following ways:
f(3), f(1.1, 2.2) and f()

C++-language
Function prototype void f();
Function has no parameters.
So the only possible way to call it is in the
form f();
This is same than void f(void)

C- and C++-language
Function prototype void f(void);
Function has no parameters.
So the only possible way to call it is in the
form f();

C++-language
Function prototype void f(...);
Nothing is determined about parameters.
So you can call it for example in the
following ways:
f(3), f(1.1, 2.2) and f()

Remark. The new versions of C-language


often support the ... as in C++

TI00AA50/JV

Function overloading
Lets assume that we have two types Tpoint and Ttriangle and we need the functions that read
information into variables of these types. These types and functions are used in the same program.

C-language
We need different names for the functions:
void read_point(Tpoint *point);
void read_triangle(Ttriangle
*triangle);
int main (void) {
Tpoint p;
Ttriangle t;

C++-language
We can use function overloading and define
several functions that all have the same
name:
void read(Tpoint *point);
void read(Ttriangle *triangle);
int main (void) {
Tpoint p;
Ttriangle t;

read_point(&p);
read_triangle(&t);
...

read(&p);
read(&t);
...

}
}

TI00AA50/JV

Operator overloading
Lets assume that we want to implement an ADT for complex number calculations

C-language
We could write an ADT that we could use in
the following way:
#include "complex.h"
void main(void) {
Tcomplex a, b, c;
read_complex(&a);
read_complex(&b);
c = sum_complex(a,b);
print_complex(c);

C++-language
Now we can use operator overloading in the
implementation of the ADT. This means that
we can do input, output and addition of
complex numbers in the way we are used to
use for other numbers (ints or floats). This
means that our main program becomes
generic.
#include "complex.h"
void main(void) {
Tcomplex a, b, c;

}
cin >> a;
cin >> b;
c = a + b;
cout << c;
}

Remark. This program is


generic. It works even for
floats when only the
typename is changed
This reads from the keyboard
(cin, console input)
This writes to the screen
(cout, console output)

TI00AA50/JV

10

Default parameters
(We now assume that x is a column number and y is a row number)
// function prototype
void outputxy(const char *text, int x=-1, int y=-1);
// How to use the function in the main function
outputxy("C-language", 35, 3);
// output goes to column 35 at row 3
outputxy("C++-language");
// the new text follows the previous one
outputxy("Java-language", 10);
// the output goes to column 10 at the current row
// The implementation of the function
void outputxy(const char *text, int x, int y) {
if (x==-1) x = wherex();
if (y==-1) y = wherey();
gotoxy(x,y);
cout << text;
}

TI00AA50/JV

11

Data type bool

In C-language int type is used as a boolean


value
In C++-language there is a type bool for this
purpose The variable of type bool can have
values false or true

Sometimes it is useful to use int as boolean


and as a value at the same time
int main( ) {
int coins = 100;
while (coins) {
play();
coins--;
}

int main( ) {
bool rich;
int money = 20000;
rich = money > 10000;
// or rich = true;
if (rich) // if (rich==true)
spend_money();

return 0;
}

return 0;
}

TI00AA50/JV

12

Reference parameters and


returning a reference
Reference parameters in C++ make it easier to
use and develop the functions that modify their
parameters
The compiler takes care that reference parameters
are regarded internally as pointers
The request to the compiler is given in one place
This place is the function headline

Function can also return a reference

TI00AA50/JV

13

Comparing pointer parameters


and reference parameters
Pointer parameters

Reference parameters

// prototype of swap
void swap(int *a, int *b);

// prototype of swap
void swap(int &a, int &b);

// application
void main(void) {
in number1 = 1, number2 = 2;

// application
void main(void) {
in number1 = 1, number2 = 2;

swap(&number1, &number2);

swap(number1, number2); //ptrs are passed


instead of values
printf("%d %d", number1, number2);

printf("%d %d", number1, number2);


}

// implementation of swap
void swap(int *a, int *b) {
int aux;
aux = *a;
*a = *b;
*b = aux;
}

// implementation of swap
void swap(int &a, int &b) {
int aux;
aux = a;
//deferencing is used internally
a = b;
//with a and b
b = aux;
}

TI00AA50/JV

14

Returning a pointer and


returning a reference
Returning a pointer

Returning a reference

// prototype of a function
int *getMax(int *arr, int n);

// prototype of a function
int &getMax(int *arr, int n);

// application
int main(void) {
int maxValue;
int array[6] = {3, 5, 2, 8, 6, 7};
printf ("%d", *getMax(array, 6));
//Right value
maxValue = *getMax(array, 6);
*getMax(array, 6) = *getMax(array, 6)*10;
//Left value

// application
int main(void) {
int maxValue;
int array[6] = {3, 5, 2, 8, 6, 7};
printf ("%d", getMax(array, 6));
//Right value
maxValue = getMax(array, 6);
getMax(array, 6) = getMax(array, 6)*10;
//Left value

// implementation getMax
int *getMax(int *arr, int n) {
int i, maxi = 0;
for (i = 1; i < n; i++)
if (arr[i] > arr[maxi])
maxi = i;
return &arr[maxi];
}

// implementation getMax
int &getMax(int *arr, int n) {
int i, maxi = 0;
for (i = 1; i < n; i++)
if (arr [i] > arr[maxi])
maxi = i;
return arr[maxi];
}

TI00AA50/JV

15

Why pointer parameters are


needed in C?
Value parameters

Pointer parameters

// prototype of swap

// prototype of swap

void swap(int a, int b);

void swap(int *a, int *b);

// application
int main(void) {
in number1 = 1, number2 = 2;

// application
int main(void) {
in number1 = 1, number2 = 2;

swap(number1, number2);

swap(&number1, &number2);

printf("%d %d", number1, number2);


//the order is still 1 2 !
// swap does not work!

printf("%d %d", number1, number2);


//the order 2 1 !
// swap works correctly

// implementation of swap
void swap(int a, int b) {
int aux;
aux = a;
//the contents are changed in
here
a = b;
b = aux;
}

// implementation of swap
void swap(int *a, int *b) {
int aux;
aux = *a; //the contents are changed
in the main
*a = *b;
*b = aux;
}

TI00AA50/JV

16

Using dynamic memory


C

C++

Simple variable

Simple variable

int *p;
p = (int*)malloc(sizeof(int));
*p = 7;
...
free(p);

int *p;
p = new int;
*p = 7;
// or p = new int (7);
...
delete p;

Array

Array

int *a;
a = (int*)malloc(n*sizeof(int));
a[0] = 1; a[1] = 2;
...
free(a);

Differences between function malloc and operator new:


1)
2)
3)

int *a;
a = new int [n];
a[0] = 1; a[1] = 2;
...
delete a;

new calls constructor


new is simpler to use
malloc is a function, new is an operator

Differences between function free and operator delete:


1)
2)

delete calls destructor


free is a function, delete is an operator

TI00AA50/JV

17

Using build-in input and output


objects
There are many build-in
classes and objects in C++ for
different purposes like:

Input/Output
Input object cin is an instance of
the class istream and output
object cout is an instance of the
class ostream

Input and output (keyboard and


display)
File handling
String manipulation
Storing data items in different
containers (container classes)

These objects have many


member functions and overloaded
operators
The most widely used operators
are input operator >> and output
operator <<

Input/Output
Input and output objects cin and
cout are ready-to-use objects
(they are instances of classes,
declared in the system)

float a;
cin >> a;

//
//
//
cout << a; //
//
//

input is read from the keyboard,


converted into float format and stored in
the variable a
the contents of variable a is
converted to characters and displayed on
the screen

Note! Operator overloading, function overloading and reference parameters


are needed in the above example

TI00AA50/JV

18

More differences 1

Initialization of a variable

Comments

C-language:

int a = 0; // This is an initialization


int b;
b = 0;
// This is an assignment

C++-language:
Initialization and assignment can
be done as above
In C++ there is also another way
to initialize a variable:

Strictly speaking // is a comment only


in C++, not in C
Some C-compilers give a warning if
you use // comments in C-program

int a(0); // This is an


initialization and works only in
C++

In C++ it is also possible to


initialize a variable that is
allocated from the dynamic
memory (with the new operator):
int *p;
p = new int(7); // Allocates and
initializes int-variable

TI00AA50/JV

C and C++ -compilers always accept /* */


comments

Headers

C++-headers does not have .h


extension
If you use C-libraries in C++ use
header name that you get by dropping
the extension and by prefixing with c.
#include <iostream> // C++ header
#include <cstdlib> // Corresponds the
header stdlib.h in C
#include <cstring> // Corresponds the
header string.h in C
#include <string> // C++ has its own
string class

19

More differences 2

Name spaces

All names (identifiers) that belong to C++ are defined in the namespace std
Using names in the namespace is possible only by specifying also the namespace. There
are two options to do that.

Option 1. You can specify the namespace every time you use the name:

std::cout << "This goes to the screen" << std::endl;

Option 2. You and tell in the beginning of the program what namespaces you are going to use:

using namespace std;

cout << "This goes to the screen" << endl;

In large software projects there is a big probability that different modules want to use similar
names, thus we have the concept of (separate) namespaces

Prototypes of the functions

C++-language:

The prototype of the function is required before the function call. Otherwise you get an error message from the
compiler

C-language:

C-compiler compiles the function call even it has no prototype. The compiler cannot check whether you have
called the function in the correct way. The compiled program can work in totally wrong way, if you have called it
in wrong way (parameter types are not correct for example).

TI00AA50/JV

20

More differences 3
The basic idea of these operators
is to indicate the purpose of the
cast
Dynamic cast also does the
runtime check whether the type of
the object to be cast is
compatible with the new type

Automatic type casts


C++ is more strict in doing
automatic type casts than C
void *p; double *pd, int *pi;
p = pd; // OK in C and in C++
pd = p; // OK in C but error
in C++
pd = pi; // warning in C but
error in C++

New way to do type casts in


C++
Different type cast operators in
C++

static_cast
reinterpret_cast
const_cast
dynamic_cast

void *p; double *pd;


pd = (double*)p;
pd = static_cast<double*>(p);

// From C
// Same thing in
// the new way in C++

void display (char *str);


int main () {
const char *s = "abcdefg";
display (const_cast<char *> (s));
return 0;
}

TI00AA50/JV

21

Potrebbero piacerti anche