+ All Categories
Home > Documents > Lecture 01 - C++

Lecture 01 - C++

Date post: 10-Dec-2015
Category:
Upload: inuyashahot
View: 12 times
Download: 2 times
Share this document with a friend
Description:
C++ Lecture1
Popular Tags:
21
C++ Programming TI00AA50 Lecture 1 - 10.09.2015 [email protected] Pterois volitans, efficient (it eats smaller fishes fast), but extremely poisonous – just like C++
Transcript
Page 1: Lecture 01 - C++

C++ ProgrammingTI00AA50

Lecture 1 - 10.09.2015

[email protected]

Pterois volitans, efficient (it eats smaller fishes fast),but extremely poisonous – just like C++

Page 2: Lecture 01 - 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 2

Page 3: Lecture 01 - C++

TI00AA50/JV 3

General information

• WinhaWille system is used to enroll the course– You’ll 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

• Practical aim of this course– Learning practical object orienting programming using C++ programming language

• Official aims of this course– 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)

Page 4: Lecture 01 - C++

TI00AA50/JV 4

General information• Prerequisites:

– C programming language (mandatory)• Pointers, structures, prototypes, defined types

– Java programming language (recommended)• Basic object oriented concepts

– Algorithms and Data Structures course (recommended)• Algorithms, ADT, trees, dynamic memory, recursion

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

• This course is located to period 1 and 2• The extent of the course is 5 op

– 2 h lectures/ one week (2×7-1 times, 26 h together) – Lab. work 2 h / week (2×7-1 times, 26 h together) – Self study (42h) – Two simultaneous lab groups

• Exam at the end of the course (2h)– Note that there is no exam at the end of the first period– If you don’t pass the exam, you can attend a resit exam after the course exam. For the resit exam dates, look for the Tuubi-portal’s workspace

(Tuubi>For student>Important dates>re-examination dates>Technology (for Finnish: Tuubi>Opiskelijoille>Aikataulut>Uusintakoepäivät>Tekniikka, työtila TiVi Leppävaara: 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 course’s main exam)• This course belongs to the resit exam group A1

• Supporting books (not mandatory):– 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)– Koskimies: Oliokirja, Satku, 2000 (in Finnish)

• Useful links– 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)

Page 5: Lecture 01 - C++

TI00AA50/JV 5

General information

• We have 13 lab assignments– You get one credit point from one exercise

• 0.25 can be added to the credit point depending how bad/good you have performed

– 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• 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

[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

Page 6: Lecture 01 - C++

TI00AA50/JV 6

TimetableLecture Topic

1 Intro, differences between C and C++

2 Introduction to the object oriented programming

3 Constructors and destructors

4 Operator overloading

5 String class

6 Static/dynamic arrays, static class members

7 Composition and association class relations

8 Basics of inheritance

9 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

Page 7: Lecture 01 - C++

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:

– Function overloading

– Operator overloading

– Default parameters

– Reference parameters

– Inline-functions

– Etc.

TI00AA50/JV 7

CC++

e.g. void f();

Page 8: Lecture 01 - C++

Function prototype f()

• C-languageFunction prototype void f();

Nothing is determined about parametersSo you can call it for example in thefollowing ways:

f(3), f(1.1, 2.2) and f()

• C- and C++-languageFunction prototype void f(void);

Function has no parameters.So the only possible way to call it is in theform f();

• Remark. The new versions of C-language often support the ... as in C++

• C++-languageFunction prototype void f();

Function has no parameters.So the only possible way to call it is in theform f();This is same than void f(void)

• C++-languageFunction prototype void f(...);

Nothing is determined about parameters.So you can call it for example in thefollowing ways: f(3), f(1.1, 2.2) and f()

TI00AA50/JV 8

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

Page 9: Lecture 01 - C++

Function overloading

• C-languageWe need different names for the functions:void read_point(Tpoint *point);void read_triangle(Ttriangle*triangle);

int main (void) {Tpoint p;Ttriangle t;

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

...}

• C++-languageWe 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(&p);read(&t);

...}

TI00AA50/JV 9

Let’s 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.

Page 10: Lecture 01 - C++

Operator overloading

• C-languageWe 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++-languageNow 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;

}

TI00AA50/JV 10

Let’s assume that we want to implement an ADT for complex number calculations

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)

Page 11: Lecture 01 - C++

Default parameters

TI00AA50/JV 11

(We now assume that x is a column number and y is a row number)

// function prototypevoid outputxy(const char *text, int x=-1, int y=-1);

// How to use the function in the main functionoutputxy("C-language", 35, 3); // output goes to column 35 at row 3outputxy("C++-language"); // the new text follows the previous oneoutputxy("Java-language", 10); // the output goes to column 10 at the current row

// The implementation of the functionvoid outputxy(const char *text, int x, int y) {

if (x==-1) x = wherex();if (y==-1) y = wherey();gotoxy(x,y);cout << text;

}

Page 12: Lecture 01 - C++

Data type bool

• In C-language int type is used as a booleanvalue

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

int main( ) {bool rich;int money = 20000;

rich = money > 10000;// or rich = true; if (rich) // if (rich==true)

spend_money();

return 0;}

• Sometimes it is useful to use int as booleanand as a value at the same time

int main( ) {int coins = 100;

while (coins) {play();coins--;

}

return 0;}

TI00AA50/JV 12

Page 13: Lecture 01 - C++

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

Page 14: Lecture 01 - C++

Pointer parameters

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

// applicationvoid main(void) {

in number1 = 1, number2 = 2;

swap(&number1, &number2);

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

// implementation of swapvoid swap(int *a, int *b) {

int aux;aux = *a;*a = *b;*b = aux;

}

Reference parameters

Comparing pointer parameters and reference parameters

// prototype of swap

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

// applicationvoid main(void) {

in number1 = 1, number2 = 2;

swap(number1, number2); //ptrs are passed instead of valuesprintf("%d %d", number1, number2);

}

// implementation of swapvoid swap(int &a, int &b) {

int aux;aux = a; //deferencing is used internallya = b; //with a and bb = aux;

}

TI00AA50/JV 14

Page 15: Lecture 01 - C++

Returning a pointer

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

// applicationint main(void) {

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

}

// implementation getMaxint *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];}

Returning a reference

Returning a pointer and returning a reference

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

// applicationint main(void) {

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

//Left value

}

// implementation getMaxint &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

Page 16: Lecture 01 - C++

Value parameters

// prototype of swap

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

// applicationint main(void) {

in number1 = 1, number2 = 2;

swap(&number1, &number2);

printf("%d %d", number1, number2);//the order 2 1 !// swap works correctly

}

// implementation of swapvoid swap(int *a, int *b) {

int aux;aux = *a; //the contents are changed in the main*a = *b;*b = aux;

}

Pointer parameters

Why pointer parameters are needed in C?

// prototype of swap

void swap(int a, int b);

// applicationint main(void) {

in number1 = 1, number2 = 2;

swap(number1, number2);

printf("%d %d", number1, number2); //the order is still 1 2 !// swap does not work!

}

// implementation of swapvoid swap(int a, int b) {

int aux;aux = a; //the contents are changed in here a = b; b = aux;

}

TI00AA50/JV 16

Page 17: Lecture 01 - C++

Using dynamic memory

• Differences between function malloc and operator new:

1) new calls constructor

2) new is simpler to use

3) malloc is a function, new is an operator

• Differences between function free and operator delete:

1) delete calls destructor

2) free is a function, delete is an operator TI00AA50/JV 17

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);

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

Page 18: Lecture 01 - C++

Using build-in input and output objects

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

– Input and output (keyboard and display)

– File handling

– String manipulation

– Storing data items in different containers (container classes)

• Input/Output– Input and output objects cin and

cout are ready-to-use objects

(they are instances of classes, declared in the system)

• Input/Output– Input object cin is an instance of

the class istream and output object cout is an instance of the class ostream

– These objects have many member functions and overloaded operators

– The most widely used operators are input operator >> and output operator <<

TI00AA50/JV 18

float a;cin >> a; // input is read from the keyboard,

// converted into float format and stored in// the variable a

cout << 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

Page 19: Lecture 01 - C++

More differences 1

• Initialization of a variable– C-language:

int a = 0; // This is an initializationint 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: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

• Comments– Strictly speaking // is a comment only

in C++, not in C

– Some C-compilers give a warning if you use // comments in C-program

• 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 it’s own string class

TI00AA50/JV 19

Page 20: Lecture 01 - C++

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

Page 21: Lecture 01 - C++

More differences 3

• 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

– 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

TI00AA50/JV 21

void *p; double *pd;pd = (double*)p; // From Cpd = static_cast<double*>(p); // 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;}


Recommended