Vous êtes sur la page 1sur 31

Contents

Session 1 – 1.09.2017 .......................................................................................................... 3


1. Creating a new C++ project in Visual Studio. ................................................................. 3
2. Create the first C++ program, “Hello World!”. ................................................................. 4
3. Creating another method and call it in the main method. ............................................... 5
4. Pointers ......................................................................................................................... 6
5. Other debates ................................................................................................................ 7
Session 2 – 8.09.2017 .......................................................................................................... 9
1. Using cin/cout (Standard Input) ...................................................................................... 9
2. Addresses ...................................................................................................................... 9
3. A limited set of arithmetic operations can be performed on pointers............................... 9
4. Malloc/ Calloc/ Realloc/ Free.........................................................................................10
5. Struct: ...........................................................................................................................11
Session 3 – 15.09.2017 .......................................................................................................13
1. Better types in C++11 – nullptr, enum classes. .............................................................13
2. Mechanisms to transfer/pass parameters .....................................................................14
3. Overloads .....................................................................................................................15
4. Double pointers .............................................................................................................15
5. Using new/delete ..........................................................................................................15
6. Classes .........................................................................................................................16
6.1. Objects ...................................................................................................................16
6.2. Access specifiers ....................................................................................................17
6.3. Constructor .............................................................................................................17
6.4. Destructor ...............................................................................................................18
Session 4 – 22.09.2017 .......................................................................................................19
1. Topics from last discussion: ..........................................................................................19
2. Classes – copy constructor ...........................................................................................19
3. Classes – assignment operators ...................................................................................21
Session 5 – 29.09.2017 .......................................................................................................22
1. Classes’ inheritance ......................................................................................................22
2. Copy Constructor call ....................................................................................................22
3. Practice with classes: ....................................................................................................23

- Vertraulich / Confidential -
Session 6 – 6.09.2017 .........................................................................................................24
1. Multiple inheritance .......................................................................................................24
2. Initializer – table (old/new) ............................................................................................24
Session 7 – 3.11.2017 .........................................................................................................26
1. Pointer to functions (C-style) .........................................................................................26
2. Auto ..............................................................................................................................26
3. Polymorphism ...............................................................................................................26
3.1. Pointers to base class – pointer to derived class type-compatible with a pointer to its
base class. ....................................................................................................................27
3.2. Virtual members .....................................................................................................28
3.3. Abstract base classes .............................................................................................28
3.4. Override .................................................................................................................28
4. Lambda expressions .....................................................................................................29
5. Static members .............................................................................................................29

- Vertraulich / Confidential -
Session 1 – 1.09.2017
Prerequisite: Visual Studio 2015

1. Creating a new C++ project in Visual Studio.

File -> New -> Project

In New Project Window, choose Visual C++, Empty Project. You may choose the location and the
name of the project also.

After clicking ok, the project is created. Now we need to add the first source file. For that, right click
on “Source Files” in Solution Explorer and then Add-> New File. Create the file Main.cpp.

- Vertraulich / Confidential -
2. Create the first C++ program, “Hello World!”.

Line by line explanations:


 We need to include the file <iostream>, which is the header that defines the standard
input/output stream objects. We need it because we will use cout – to display the text in the
console.
 We need to use the namespace std. Namespaces provide a method for preventing name
conflicts in large projects. We may explicit write the namespace in front of the called
method, like:

- Vertraulich / Confidential -
 Then we have the body of the main method, which is designated start of the program. We
may have several declarations for main, we used it the one without parameters. The method
is returning 0 which means that no error occurred.
 In the end we display “Hello world!” in the console.
 First build the solution (Menu -> Build -> Build Solution – F6), then run the project:

3. Creating another method and call it in the main method.

We will write a method that receives a number and returns number + 1.

- Vertraulich / Confidential -
We may observe that the method is not defined inside a class. It is defined as free function.
The function has a global scope, meaning it can be accessed from anywhere, if you know its
signature.

4. Pointers
 C++ offers you the power to manipulate the data in the memory of the computer. You may
allocate or de-allocate memory as you wish. This is done using Pointer variables.
 Pointers are variables that points to a specific address in the memory, pointed by another
variable.

 Examples discussed:
o Pointer is like shortcut – pointing to an executable of the file. You may change the
“.exe” that is pointing to.
o Pointer is like an address card.
 How to declare a pointer:

- Vertraulich / Confidential -
This is a pointer to a variable of type int. We may also declare one of type char:

 Allocate memory for the pointer (in this example 5 integers – 5 * sizeof(int) bytes)

 Deallocate the memory for the pointer:

 Sizeof operator – queries size of the object or type

 Initialize the vector:

Or the modern way, using initializer list:

 Display the address of the pointer variable, the address of the first pointed element in the
vector:

5. Other debates
 We may print the entire charPointer without loop into it:

 Why the delete method doesn’t put the member to nullptr directly. Maybe one reason may
be const pointers.

- Vertraulich / Confidential -
 Differences between struct type and class type
The members and base classes of a struct are public by default, while in class, they default to
private. Note: you should make your base classes explicitly public, private, or protected,
rather than relying on the defaults.
Struct and class are otherwise functionally equivalent.

 “using”:
o using just one method from the entire namespace: using std::cout;
o inside a function block:
void function()
{
using namespace std;
}

- Vertraulich / Confidential -
Session 2 – 8.09.2017

1. Using cin/cout (Standard Input)


cin Is used together with the extraction operator >> (2 greater signs). The operator is
followed by the variable where the extracted data is stored.
o For instance:
o int number; cin >> number;
 <iostream> defines the cin (standard input stream), cout (standard output stream), cerr (un-
buffered standard error stream) and clog (buffered standard error stream) objects.
 endl – means end of line and sends a new line. Equivalent with “\n”.
 we may write also cout<<a<<endl<<b<<” “;

2. Addresses

3. A limited set of arithmetic operations can be performed on pointers.


A pointer may be:
o incremented ( ++ )
o decremented ( — )
o an integer may be added to a pointer ( + or += )
o an integer may be subtracted from a pointer ( – or -= )

- Vertraulich / Confidential -
The incrementation of the pointer will move sizeof(T) bytes. For instance if you point to an
int which is 4 bytes in size the incrementation will move with 4 bytes.
For testing you may print the addresses:

4. Malloc/ Calloc/ Realloc/ Free


o Malloc – allocates memory and returns pointer to the allocated memory.
 Signature: void *malloc(size_t size);
 Example: int * ptr = (int*) malloc(10 * sizeof(int));
 if the memory is not able to allocate the requested memory on heap then
malloc returns NULL;
 memory is not initialized;
 In theory the pointer should be checked because malloc may return NULL.
o Calloc – memory allocation + initialization (with 0)
 Signature: void* calloc( size_t num, size_t size );
 Example: int * ptr = (int*) calloc(1, sizeof(int));
 same as malloc
o Realloc – change the size of memory block on heap
 Signature: void *realloc(void *ptr, size_t size);
 Example
For instance pointer ptr – pointing to a memory of 10 int on heap allocating
using malloc:

- Vertraulich / Confidential -
int * ptr = (int*)malloc(10*sizeof(int));
You need to increase the size of the ptr from 10 to 20, without losing the
content.
o Free- free the memory allocated using malloc, calloc and realloc.
 Signature: void free(void* ptr);
 if ptr is NULL, then free does nothing and returns
 Behavior is undefined on memory which is not on heap.

5. Struct:

You may read/write members using “.” operator:

- Vertraulich / Confidential -
Allocate memory for a struct:

- Vertraulich / Confidential -
Session 3 – 15.09.2017

1. Better types in C++11 – nullptr, enum classes.


 Strongly typed enums
o Old C++ enums are integers – they may be compared with integers with other enums
of different types. The questions is why comparing types of cars with types of food?
o with strongly type enums, the compiler will tell you about this comparisons;
o Examples:
Code that will not compile:

Code that will compile (if compiler supports C++ 11)

o Accessing the enum values:

o We can have a forward declaration to a strongly typed enum (by doing this the
possible enum values may be changed without forcing all dependent files to
recompile).

- Vertraulich / Confidential -
 std::nullptr_t
o nullptr – C++ (11) has a keyword that designates a null pointer constant.
o nullptr replaces the NULL macro that have been used as null pointer substitutes for
many years.
o Example:
void f(int) // #1
void f(char *) // #2
f(0) // which f is called
// c++ 11
f(nullptr) // calls #2

2. Mechanisms to transfer/pass parameters

Difference between references and pointers


o A pointer variable is a variable which holds the memory address of some other
variable.
o A reference variable is a variable which “refers to” another named or unnamed
variable.

Some major attributes of pointers that differentiate them from references:


 You use pointer syntax to access the values "pointed to" by the pointer.
 You can redirect the pointer to point it to a different "target" variable.
 You can make a pointer point to nothing (NULL pointer).
Then references:
 References must be initialized at the point of instantiation.
 References must ALWAYS "refer to" a named or unnamed variable (that is, you
cannot have a reference variable that refers to nothing, the equivalent of a NULL
pointer).
 Once a reference is set to refer to a particular variable, you cannot, during its
lifetime, "rebind" it to refer to a different variable.
 You use normal "value" syntax to access the value being referred to.

- Vertraulich / Confidential -
3. Overloads
In C++ - two different functions can have the same name if their parameters are different
(different number or a different type).

4. Double pointers

5. Using new/delete
We saw in the last session how may we allocate or deallocate the memory using the
C-style : malloc/realloc/calloc/free.
Allocating and deallocating memory with new and delete (C++ style).

The memory is dynamically allocated using the operator new. new is followed by the data
type specified and for more than 1 element brackets are used [].
pointer = new type
pointer = new type [number_of_elements]

- Vertraulich / Confidential -
Example:
int *x = new int;
// C-Style
int *x = (int *) malloc (sizeof(int));
delete x;
x = new int[10];

int *x2 = new int[10];


// C-Style
int *x2 = (int *) malloc (sizeof(int)*10);

The system dynamically allocates space for 10 elements of type int and returns a pointer to
the first element of the block, which is assigned to x (the pointer).
You may access the first element using *x or x[0].

New may also fail and to prevent that (well not really our case):
- you may handle the exception bad_alloc (when allocation fails);
- you may use the method known as nothrow and when memory allocation fails, the pointer
returned will be a null pointer:
x = new (nothrow) int [10];

If the memory is no longer used the delete operator is used.


delete x; // deletes a single element
delete [] x; // deletes memory allocated for arrays of elements.

Attention: the memory SHOULD be allocated previously with NEW.

6. Classes
 Classes are an expanded concept of data structures: like data structures, they can
contain data members, but they can also contain functions as members.
 An object is an instantiation of a class. In terms of variables, a class would be the
type, and an object would be the variable.
 Classes are declared in header, with the keyword “class”. In header the variables but
also the methods are declared. The definition of the methods are written in a *.cpp
file. When the methods are defined in cpp, we should specify the class followed by
the resolution operator “::”.

6.1. Objects
To instantiate a class you need to declare an object of its type.

You may also use a pointer to the class:

Or you may also use a vector of Employee ():

- Vertraulich / Confidential -
The access to the members is realized (same as structures) with the “.” operator for
the objects static defined and operator “->” for pointers.

6.2. Access specifiers


The access specifiers define the visibility of the members/methods inside the same
class.
For derived class – define the accessibility of inherited members.

Syntax (from cppreference.com):

6.3. Constructor
A constructor is called automatically when an object of the class is created. It is used
for initialize variables or allocate memory.

Default constructor (empty parameters or default arguments provided for every


parameter)

We may overload the constructor with a different versions taking different


parameters, same as we do with usual methods:

- Vertraulich / Confidential -
From C++11
ClassName() = delete;
This is inhibiting the automatic generation of a default constructor by the compiler.
Example: static class – no instantiation needed
ClassName() = default;
Explicitly forcing the automatic generation of a default constructor by the compiler.

Explicit
http://en.cppreference.com/w/cpp/language/explicit

6.4. Destructor
A destructor is called automatically when an object of the class is deleted, or it is out
of scope (lifetime of an object ends). It is used to free the resources of the object.

Syntax:

- Vertraulich / Confidential -
Session 4 – 22.09.2017
1. Topics from last discussion:
 Once a reference is set to refer to a particular variable, you cannot, during its lifetime,
"rebind" it to refer to a different variable.

What is happening in the current scenario?


Line by line description:
o declare a new pointer to int, to one element;
o put the value 5 on it;
o declare an address and bind it to the pointer;
o display both values;
o declare another pointer to int, to one element;
o Put value 20 in the second pointer.
o “bind” again the same address to the second pointer;
o Display all 3 values.

We may easily observed that the value of the firstPointer now is 20. Why?
Once again, you cannot “rebind” the reference to a different variable. It will assign the value of the
second pointer to the value referenced by ref, the first pointer.
We may compare the reference with a const pointer.

2. Classes – copy constructor

(1) Typical declaration of a copy constructor


(2) Forcing a copy constructor to be generated by the compiler
(3) Avoiding implicit generation of copy constructor.

Example:
Declaration in header.

- Vertraulich / Confidential -
Definition in cpp file:

The copy constructor is called whenever an object is initialized (by direct-initialization or copy-
initialization) from another object of same type.
Examples (direct initialization and copy-initialization).

Question: what happens when using pointers?

Other places where copy-constructor is used.


o function argument passing

Function return (where the return type is type of the class and the class has no move constructor!)

- Vertraulich / Confidential -
3. Classes – assignment operators

Example

- Vertraulich / Confidential -
Session 5 – 29.09.2017
1. Classes’ inheritance

Classes in C++ may be extended. The process is called inheritance. This process involves a base class
and a derived class. The derived class inherits members of the base class and on top of these
members it may add its own members.

The inheritance relationship is specified in the derived class:

2. Copy Constructor call


Copy constructor of the derived class doesn’t call automatically the copy constructor of the base
class.
This should be specified in the code.

- Vertraulich / Confidential -
The same things is happening also with the assignment operator:

3. Practice with classes:


 Implement a base class that contains constructor, copy constructor, assignment operator,
destructor and at least a pointer.
 Implement a derived class from the base class;
 make instances of the classes, use also pointers;
 try to call constructor, destructor, copy constructor, assignment operator;
 use public/protected/private inheritance;
 test order of constructors/destructors;

- Vertraulich / Confidential -
Session 6 – 6.09.2017
1. Multiple inheritance
C++ supports multiple inheritance. That means that a class may inherit members/methods from
multiple classes.
If the multiple inheritance is not properly used, it may lead to problems.

One of the problem is the diamond problem.

2. Initializer – table (old/new)


https://www.youtube.com/watch?v=iWvcoIKSaoc

Syntax without initializer (before modern C++) Syntax with initializer


int a = 1; int a{1}
string s = “foo”; string s{ "foo" };
std::vector<int>values; std::vector<int>values {1,2,3};
values.push_back(1);
values.push_back(2);
std::map<string, string> capitals; map<string, string> capitals {
capitals.insert(std::make_pair( "UK", "London" )); { "UK", "London" }
};

- Vertraulich / Confidential -
struct Person struct Person
{ {
string name; string name;
int age; int age;
}; };

Person p; Person p { “John” , 123};


p.name = “John”;
p.age = 123;
struct Exchange struct Exchange
{ {
int count; int count;
float rates[2]; float rates[2];
}; };

Exchange e; Exchange e { 1, 2, 3 };
e.count = 1;
e.rates[0] = 2;
e.rates[1] = 3;

- Vertraulich / Confidential -
Session 7 – 24.11.2017
1. Pointer to functions (C-style)

..And the call in main function:

2. Auto
int
float
const wchar *
Initializer list

3. Polymorphism

To understand this concept, information about inheritance and pointers is required.

- Vertraulich / Confidential -
3.1. Pointers to base class – pointer to derived class type-compatible with a pointer to its base class.

- Vertraulich / Confidential -
3.2. Virtual members

3.3. Abstract base classes


There are base classes that cannot be instantiated. They are only base classes that offer methods
without definitions (pure virtual functions).

3.4. Override

- Vertraulich / Confidential -
https://www.youtube.com/watch?v=iWvcoIKSaoc

Make examples.

Session 8 – 08.12.2017

4. Lambda expressions

5. Static members

Idea: where the memory is allocated?


Compile time/ runtime

- Vertraulich / Confidential -
Next:
 inline/ coding guidelines (cpp/header) – Adrian?
 const/ static
 classes – move constructor, pointer this
 casts (static_cast, dynamic_cast, const_cast, reinterpret_cast)
 lambda expressions
 smart pointers

Interesting concepts

The rule of three/five/zero

 Rule of three
If a class requires a user-defined destructor, a user-defined copy constructor, or a user-
defined copy assignment operator, it almost certainly requires all three.

 Rule of five
Because the presence of a user-defined destructor, copy-constructor, or copy-assignment
operator prevents implicit definition of the move constructor and the move assignment
operator, any class for which move semantics are desirable, has to declare all five special
member functions.

 Rule of zero
Classes that have custom destructors, copy/move constructors or copy/move assignment
operators should deal exclusively with ownership (which follows from the Single
Responsibility Principle). Other classes should not have custom destructors, copy/move
constructors or copy/move assignment operators.

noexcept operator (C++11)


What means to declare a function as noexcept?
It terminates exceptions or the function is not throwing any exceptions.

- Vertraulich / Confidential -
Good references:
 http://en.cppreference.com
 http://www.cplusplus.com/doc/tutorial/
 https://www.tutorialspoint.com/cplusplus/

Sources used:
https://en.wikibooks.org/wiki/C%2B%2B_Programming/Operators/Pointers
http://www.cprogramming.com/c++11/c++11-nullptr-strongly-typed-enum-class.html
http://www.cplusplus.com/doc/tutorial/dynamic/
http://en.cppreference.com/w/cpp/language/rule_of_three
http://en.cppreference.com/w/cpp/language/copy_constructor
http://www.cplusplus.com/doc/tutorial/polymorphism/
http://en.cppreference.com/w/cpp/language/override

- Vertraulich / Confidential -

Vous aimerez peut-être aussi