C++

Let's discover a new world !

c to C++



Many similar code

but C++ is not C, as C is not C++ !


Let's get into these differences ...

summary


Variables
I/O operators
New types
Control structures
Functions
Arrays
Pointers

Variables: Declaration


First way, the same as C language
type name = value;
int numberOfApples = 50;

Second way, only for C++
type name(value);
int numberOfBananas(32);

Both of them are correct, 
but we will prefer the second one

Variables: Into the memory


int myAge(50); 

This operation is actually composed of

  • Declaration (ask the computer for some memory space)
  • Initialization (put a value in that memory space)

Variables


Declare a variable without initializing it

int numberOfPlayers;
double score;

Variables


Modify the content of a variable

by a value
int a(0);a = 41;

by the content of another variable
int a(50);int b(23);a = b;

variables


constant: variable unmodifiable

double const pi(3.14);

Variables


Let's give another name to a variable: using a reference!

int myAge(50);
int& myAgeCopy(myAge);
printf("myAge = %i\n", myAge);printf("myAgeCopy = %i\n", myAgeCopy);

Why ?
Let's see that later when needed

I/O operators


No more printf and scanf

No more reasons to deal with %d, %i, %f, ...

Let's welcome the Input/Output operators !

I/O operators


Here is the default code proposed by Code::Blocks when creating a new C++ project:

#include <iostream>using namespace std;
int main(){ cout << "Hello world!" << endl; return0;}

I/O OPERATORS


Cout is far easier to use than printf:
everything using "<<"

int myAge(50);cout << "myAge: " << myAge << endl;

No need for %d, %s, ... anymore !

I/O OPERATORS


Cin instead of scanf:
everything using ">>"

int myAge(0);cin >> myAge;

No need for %d, %s, ... anymore !

I/O operators


Input/Output example

#include <iostream>     using namespace std;
int main(){ int myAge; cout << "How old are you?" << endl; cin >> myAge; cout << "Your Age: " << myAge << endl; return 0;}

EXERCISE 1/2


Write a code executing the following result:

Welcome in our addition software!Enter a value for a:Enter a value for b:a + b = 

Do not use C language, follow the C++ standards

Exercise 2/2


Complete your previous code by adding:

  • multiplication
  • division (quotient and remainder)

New types: string


C++ has a new type "string" to put text in it

string name = "Brice";

It works fine with cin and cout

 NEW TYPEs: string


Using "string" example

#include <iostream>     using namespace std;
int main(){ string name(""); cout << "What is your name?" << endl; cin >> name; cout << "Hello " << name << ", how are you today?" << endl; return 0;}

NEW TYPEs: bool


C++ has a new type "bool" to represent true or false

bool teacherIsGood(true);

Control structures


Programs needs to take decisions:


test variables (conditions)

repeat instructions several times (loops)

CONTROL STRUCTURES: CONDITIONS


"if" execute some instructions
if the condition is verified

unsigned int bananas(8); // unsigned: positive integer if (bananas < 5){  cout << "You need to buy some bananas" << endl;}

CONTROL STRUCTURES: CONDITIONS


"if ... else" execute some instructions
if the condition is or is not verified

unsigned int bananas(8); // unsigned: positive integer if (bananas < 5){  cout << "You need to buy some bananas" << endl;}else{  cout << "You have enough bananas" << endl;}

CONTROL STRUCTURES: CONDITIONS


"if ... else if ... else" add another test
unsigned int bananas(8); // unsigned: positive integer if (bananas <= 10 && bananas >= 3){  cout << "Do not forget to eat your bananas" << endl;}else if (bananas < 3){  cout << "You need to buy some new bananas" << endl;}else {  cout << "You bought to much bananas" << endl;}

CONTROL STRUCTURES: conditions


Tip: test several values using "switch"
unsigned int numberOfBananas(10);
switch (numberOfBananas){ case 1: // if cout << "You still have 1 banana" << endl; break; case 2: // else if cout << "You still have 2 bananas" << endl; break; [...] // else if ... else if ... else if ... default: // else cout << "You still have "<< numberOfBananas << "bananas" << endl; break;}

CONTROL STRUCTURES: CONDITIONS


Specific case: booleans

bool man(true)
if (man){ cout << "You are a man" << endl;}else{ cout << "You are a woman" << endl;}

CONTROL STRUCTURES: LOOPS


"while" and "do ... while" execute instructions again and again
as long as a condition is verified


Difference?

"while" checks the condition and execute instructions

"do ... while" execute instructions and checks the condition

CONTROL STRUCTURES: Loops


int numberOfBananas; // int is signed (can be negative)
cout << "How many bananas do you have? ";cin >> numberOfBananas;
while (numberOfBananas < 0){ cout << "Enter a correct number of bananas"; cin >> numberOfBananas;}
cout << "You have " << numberOfBananas << " bananas" << endl;

CONTROL STRUCTURES: Loops


int numberOfBananas; // int is signed (can be negative)
cout << "How many bananas do you have? ";cin >> numberOfBananas;

do{ cout << "Enter a correct number of bananas"; cin >> numberOfBananas;}while (numberOfBananas < 0);

cout << "You have " << numberOfBananas << " bananas" << endl;

CONTROL STRUCTURES: LOOPS


"for" executes instructions n times

  • declaration and initialization of a counter
  • condition
  • modification of the counter

for (init counter; condition; modif counter){  [...]  instruction;  [...]}

CONTROL STRUCTURES: LOOPS


int numberOfBananas(10);
for (int i(0); i < numberOfBananas; i++){ cout << "I ate " << i << " bananas" << endl;}

I ate 0 bananasI ate 1 bananasI ate 2 bananas...I ate 9 bananas

Functions


Here is the default code proposed by Code::Blocks when creating a new C++ project. This code already contain a function: main()

#include <iostream>using namespace std;
int main() // Every C++ programs start by running this function{ cout << "Hello world!" << endl; return0;}

functions


Cut the code in smaller parts
Use some instructions several times



A function:

  1. Can receive datas (arguments)
  2. Process its instructions
  3. Return a value as a result

Functions: skeleton


type functionName(arguments){  [...]  instructions;  [...]
return value;}

Functions: add()


int add(int a, int b){  int result;  result = a + b;  return result;}
int main(){ cout << "Write a first integer: "; cin >> int1; cout << "Write a second integer: "; cin >> int2; int int3 = add(int1, int2); cout << int1 << "+" << int2 << "=" << int3 << endl; return 0;}

Functions: void


"void" allows the creation of a function 
without a return value

void sayHello(){  cout << "Hello!" << endl;}

Functions: calls



Call by value:
data copied into a local variable


Call by reference:
local variable point to the original data

Functions: call by value


int addTwo(int a){  a = a + 2;  return a;}
int main(){ int number(6), result; result = addTwo(number); cout << "number=" << number << " and result=" << result << endl; return 0;}
// number = 6// result = 8

Functions: call by reference


int addTwo(int& a){  a = a + 2;  return a;}
int main(){ int number(6), result; result = addTwo(number); cout << "number=" << number << " and result=" << result << endl; return 0;}
// number = 8// result = 8

FUNCTIONS: CALL BY CONST REFERENCE


Faster: avoid copy
Safer: prevent modifications

void copyBook(string text) // long to copy{}
void copyBook2(string& text) // can modify original text{}
void copyBook3(string const& text) // fast copy and read-only{}

Functions: ORDERING the code



Every functions in one file ...
BAD HABIT !!!


Sort the code using several files

Functions: ordering the code


As an example, let's group all the mathematics functions. 


2 files are needed:

  • math.h (header file) containing functions prototypes
  • math.cpp (source file) containing functions implementations

functions: ORDERING THE CODE


math.h
#ifndef MATH_H_INCLUDED // Ensure to include this file only once#define MATH_H_INCLUDED // in the compilation process
// Add 2 numbers and return their sum
int add(int a, int b);
// Take number as argument and return number + 2
int addTwo(int a);
#endif

Advice: always comment the aim of the functions

functions: ORDERING THE CODE


math.cpp
#include "math.h" // Link the header
int add(int a, int b){ int result; result = a + b; return result;}
int addTwo(int a){ a = a + 2; return a;}

Functions: ORDERING THE CODE


main.cpp
#include <iostream>#include "math.h" // Link the functions of math files
int main(){ int number; cout << "Enter an integer: "; cin >> number; addTwo(number); cout << "Your number + 2 = " << number << endl;
return 0;}

Arrays



Group datas of same type together


Static arrays
Dynamic arrays
Multidimensional array

Arrays: static


The size of the array is known:
it book the exact memory space

Skeleton
 type name[size];

Example: declare an array of 5 classes
int const numberOfClasses(5); // The size of the array is knownstring classes[numberOfClasses];


ARRAYS: STATIC


Fill the array

string classes[5];
classes[0] = "B1"; // Arrays starts with the index 0classes[1] = "B2";
classes[2] = "B3";
classes[3] = "M1";
classes[4] = "M2";

ARRAYS: STATIC


Read a value
cout << "The class for B2 students is: " << classes[1] << endl;

Run through all the array
for(int i=0; i<numberOfClasses; i++) // numberOfClasses = 5{  cout << classes[i] << endl;}

Arrays: dynamic


The size of the array can change

#include <vector> // Do not forget to include the "vector" library!

Skeleton
vector<type> name(initialSize, defaultValue);

Examples
vector<double> scores;vector<string> students(5);vector<string> teachers(10, "no name");

ARRAYS: DYNAMIC


Fill the array
vector<string> students(5, "no name");

students[0] = "Justin BIEBER";students[1] = "Bruce LEE";students[2] = "Jack JOHNS";

Read it
cout << students[1] << endl; // Display Bruce LEEfor (int i=0; i<students.size(); i++) //size() returns the array size{  cout << students[i] << endl;} // Display all the students names

arrays: Dynamic


Add a value at the end of the array

vector<double> scores; // Declare an empty array
scores.push_back(18);scores.push_back(11);
for(int i=0; i<scores.size(); i++) { cout << scores[i] << endl; }

Result:
1811

arrays: Dynamic


Remove the last value of the array

vector<double> scores; // Declare an empty array
scores.push_back(18); // Add the value 18scores.push_back(11); // Add the value 11
scores.pop_back(); // Remove the last value of the array
for(int i=0; i<scores.size(); i++) { cout << scores[i] << endl; }

Result:
18

Arrays: multidimensional


An array of arrays

Skeleton
type name[sizeA][sizeB]...[sizeN];

Example
int const sizeX(5);int const sizeY(4);int scores[sizeX][sizeY];

Exercise



Write a program that asks the user to type 10 integers of an array.

The program must output the largest element in the array,
and the index at which that element was found (if the largest element appear several times, output all its indexes).

POINTERS


Each memory space in a computer can contain only
one variable, and has an address

A variable can be accessed
  • by its name
  • by its address


int myAge(30);cout << "The value of myAge is: " << myAge << endl;cout << "The address of myAge is: " << &myAge << endl;

Pointers


How to record an address and access to its value?
Using a pointer!


A pointer is a variable containing the address of another variable

Pointers: Declaration


Skeleton
type *name;
"type" must be the same type as the variable pointed to

Examples
int *p1;double *p2;sting *p3;unsigned int *p4;vector<string> *p5;

Pointers: declaration


ATTENTION !!!

If the pointer does not point to any known address
DANGER -> it could point to a system variable

Prevention
Always give the value 0 to the pointer when declaring it
type *name(0);
Example
int *p1(0);

POINTERS: INITIALIZATION


Store an address into the pointer

int myAge(30);int *myPointer(0);
myPointer = &myAge;

POINTER: USE


Display its content (an address)
cout << myPointer << endl; // Output 0x1ab23c4d for example

Display the value pointed to
cout << *myPointer << endl; // Output 30

C++ : Foundations

By bricesup

C++ : Foundations

  • 1,179