Introduction to C++

History and evolution

Creator: Bjarne Stroustrup 1983

Standards

  • The first C++ standard
    • 1998 (C++98, major)
    • 2003 (C++03, minor)
  • The second C++ standard
    • 2011 (C++11, major) - significant improvements in language and library
    • 2014 (C++14, minor)
  • Standard C++
Bjarne Stroustrup

Bjarne Stroustrup Inventor of the C++ Programming Language

Introduction to C++

Standard library

C++ standard library = C Standard library + STL (Standard Template Library)

STL - designed by Alexander Stepanov, provides:

Containers: list, vector, set, map....

Iterators

Algorithms: search, sort,...

Alexander Stepanov

Alexander Stepanov

Introduction to C++

Philosophy

  • Statically typed
  • General purpose
  • Efficient
  • Supports multiple programming styles:
    • Procedural programming
    • Object-oriented programming
    • Generic programming
Introduction to C++

The first C++ program

#include <iostream> //Preprocessor directive
using namespace std;
int main(){//the main function
	cout << "Hello World!" << endl; //I/O stream
	return 0;
}
			
#include <iostream>
int main(){
	std::cout << "Hello World!" << endl;
	return 0;
}
			
Introduction to C++

Building a C++ program: 3 steps

Proprocessor (line starting with #)

Complier

Linker

Introduction to C++

Most common preprocessor directives

#include [file]

The specified file is inserted into the code

#define [key] [value]

Every occurrence of the specified key is replaced with the specified value

#ifndef [key] .... #endif

Code blocks is conditionally included

Introduction to C++

Header files

  • C++ header
    • #include <iostream>
  • C header
    • #include <cstdio>
  • User defined header
    • #include "myheader.h"
Introduction to C++

Avoid multiple includes

//myheader.h
#ifndef MYHEADER_H
#define MYHEADER_H
//the contents
#endif
			
Introduction to C++

I/O Streams

cout: standard output

cout << "Hello World!" << endl;
			

cin: standard input

double a;
int b;
cin >> a >> b;
			
Introduction to C++

Namespaces

avoid naming conflicts

//my1.h
namespace myspace1{
	void hi();
}
			
//my2.h
namespace myspace2{
	void hi();
}
			
//my1.cpp
#include "my1.h"
namespace myspace1{
	void hi(){
		cout << "Hello" <<endl;
	}
}
			
//my2.cpp
#include "my2.h"
namespace myspace2{
	void hi(){
		cout << "Hi" << endl;
	}
}
			
Introduction to C++

Variables

can be declared almost anywhere in your code

double d; //uninitialized
int i = 10; //initialized
			
Introduction to C++

Variable types

short, int, long - range depends on compiler, but usually 2, 4, 4 bytes

float, double

bool

char

auto

string

Introduction to C++

C enumerations (not type-safe)

Always interpreted as integers

You can compare enumeration values from completely diferent types

enum Fruit{
	apple, melon, strawberry
};
enum Vegetable{
	tomato, cucumber, onition	
};
void main(){
	if(tomato == apple){
		printf("Hurra\n");
	}
}
			
Introduction to C++

C++ enumerations (type-safe)

enum class Mark{
	Undefined, Low, Medium, Hight	
};
Mark myMark(int val){
	switch(val){
		case 1: 
		case 2: return Mark::Low;
		case 3: case 4: return Mark::Medium;
		case 5: return Mark::Hight;
		default: return Mark::Undefined;
	}
}
			
Introduction to C++

Range-based for loop

int elements[] = {1, 2, 3, 4, 5, 6 };
for(int e : elements){
	cout<<e<<endl;
}
or
for(auto e: elements){
	cout<<e<<endl;
}
			
Introduction to C++

Pointers and dynamic memory

Compile time array

int ctarray[3];	//allocated on stack
			

Run time array

int * rtarray = new int[3]; //allocated on heap
Introduction to C++

Dynamic memory management

allocation

int* x = new int;
int* t = new int[3];
			

deletion

delete x;
delete []t;
			
Introduction to C++

Strings

C-style strings

array of characters

'\0' teminated

functions provided in <cstring>

C++ string

described in <string>

string firstName = "John";
string lastName = "Smith";
string name = firstName + " " + lastName;
cout << name << endl;
			
Introduction to C++

References

A reference defines an alternative name (alias) for an object

A reference must be initialized

Defining a reference = binding a reference to its initializer

int i = 10;
int &ri = i;//ok ri refers to(is another name for) i
int &ri1;// error: a reference must be initialized
			
Introduction to C++

Operations on references

The operation is always performed on the referred object

int i = 10;
int &ri = i;
++ri;
cout << i << endl;//outputs 11
++i;
cout << ri << endl;//outputs 12
			
Introduction to C++

References as function parameters

To permit pas-by-reference

allow the function to modify the value of the parameter

avoid copies

void inc(int &val){
	val++;
}
//usage:
int x = 10;
inc(x);
				
bool isShorter(const string &s1, const string &s2){
	return s1.size() < s2.size();
}
usage:
string str1 = "apple";
string str2 = "nut";
cout << str1 << "<" << str2 << ": " << isShorter(str1, str2);
				
Introduction to C++

Exceptions

Exception = unexpected situation

Exception handling = a mechanism for dealing with problems

throwing an exception - detecting an unexpected situation

catching an exception - talking appropriate action

Introduction to C++

Exceptions

#include <iostream>
#include <stdexcept>
using namespace std;
double divide( double m, double n){
	if( n == 0 ){
		throw exception();
	}else{
		return m/n;
	}
}
int main() {
	try{
		cout << divide(1, 0) << endl;
	}catch(exception e){
		cout << "Exception was caught!" << endl;
	}
}
			
Introduction to C++

The const modifier

Defining constants

const int N = 10;
int a[N];
			

Protecting a parameter

void doSomething(const string& name){
	cout << "Hello " + name << endl;
	name = "Teo";//Compiler error
}