SlideShare a Scribd company logo
1 of 147
Computer Programming II – C++
Introduction to C++
C++ as a better C
• Created by Bjarne Stroustrup in 1979 to
bring Object-Oriented Programming
(OOP) support to C language.
• First “C with classes” compiler called
“Cfront” derived from C compiler called
“CPre”.
• “C++” name change in 1983 with new
features added like virtual functions,
function overloading, references with the
& symbol, the const keyword, and single-
line comments.
• Language updated again in 1989 to
include protected and static members, as
well as multiple inheritance.
• In 1998, the C++ standards committee
published the first international standard
for C++ known as “C++98” with STL.
• http://www.trytoprogram.com/cplusplu
s-programming/history/
2
Summary
Literal Constants
Integer & real number literals
Type Example
Octal 0123
Hexadecimal 0x5B1F
int 123
unsigned int 123u
long 123l
unsigned long 123ul
float 123.45f
double 123.45
5
Boolean, Character & string literals
6
A value of true representing true.
A value of false representing false.
Character literals are surrounded by single quotations 'x’.
String literals are surrounded by single quotations "Hello".
Flow Control
The if statement
if (condition) statement;
if (x == 100) cout << "x is 100";
if (x == 100)
cout << "x is 100";
if (x == 100) {
cout << "x is ";
cout << x;
}
if (x == 100) { cout << "x is "; cout << x;}
8
The if-else statement
if (condition) statement; else statement;
if (x == 100)
cout << "x is 100";
else
cout << "x is not 100";
if (x > 0)
cout << "x is positive";
else if (x < 0)
cout << "x is negative";
else
cout << "x is 0";
9
The ?: operator
Condition? expr-if-true : expr-if-false;
cout << (x == 100? "x is 100":"x is not 100");
y = x > 100? 5 : 4;
int min(int a, int b) {
return a < b? a : b;
}
10
The switch statement
switch (expression)
{
case constant1:
statements-group-1;
break;
case constant2:
statements-group-2;
break;
.
.
.
default:
default-statements-group;
}
11
The switch statement
switch (x) {
case 1:
cout << "x is 1";
break;
case 2:
cout << "x is 2";
break;
default:
cout << "value of x unknown";
}
switch (x) {
case 1:
case 2:
case 3:
cout << "x is 1, 2 or 3";
break;
default:
cout << "x is not 1, 2 nor 3";
}
12
The while statement
while (expression) statement;
int main () {
int n = 10;
while (n>0) {
cout << n << ", ";
--n;
}
cout << "liftoff!n";
}
13
The do-while statement
do statement while (expression);
int main () {
string str;
do {
cout << "Enter text: ";
getline (cin, str);
cout << "You entered: " << str << 'n';
} while (str != "goodbye");
}
14
The for.. statement
for (initialization; condition; increase)
statement;
int main () {
for (int n=10; n>0; n--) {
cout << n << ", ";
}
cout << "liftoff!n";
}
15
The for each statement (C++11)
for (declaration : range) statement;
int main () {
string str {"Hello!"};
for (char c : str)
{
cout << "[" << c << "]";
}
cout << 'n';
}
16
The goto statement (avoid!)
goto label;
…
label: statement;
LOOP:do {
if(a == 15) {
// skip the iteration.
a = a + 1;
goto LOOP;
}
cout << "value of a: " << a << endl;
a = a + 1;
} while(a < 20);
17
The continue statement
continue;
do {
if(a == 15) {
// skip the iteration.
a = a + 1;
continue;
}
cout << "value of a: " << a << endl;
a = a + 1;
}
while(a < 20)
18
The break statement
break;
do {
cout << "value of a: " << a << endl;
a = a + 1;
if(a > 15) {
// terminate the loop
break;
}
} while(a < 20);
19
C vs. C++
Casts
C C++
int i = 0;
long l = (long) i;
int i = 0;
long l = long(i);
21
Flexible Declarations
C C++
void makeit(void)
{
int i;
char *cp;
/* imagine 2000 lines of code here */
/* allocate 100 bytes for cp */
/* 1st use of cp */
cp = malloc(100);
/* 1st use of i */
for (i = 0; i<100; ++i) {
/* do something */
}
/* more code */
}
void makeit(void)
{
// 2000 lines of code
char *cp = new char[100];
for (int i = 0; i<100; ++i) {
/* do something */
}
/* more code */
}
22
'struct' and 'union' Tags
C C++
struct foo {
int a;
float b;
}
struct foo f;
typedef struct {
int a;
float b;
} foo;
foo f;
struct foo {
int a;
float b;
}
foo f;
23
The :: Operator
C C++
int a = 2;
int main() {
int a = 5;
cout << a << endl;
cout << ::a << endl;
}
int a = 2;
int main() {
int a = 5;
cout << a << endl;
/* Cannot access
global variable (a) */
}
int x = 11;
void f4() {
int y = x; // global x
int x = 22;
y = x; // local x
}
24
'new' and 'delete'
C C++
void func(void) {
int *i;
i = (int *) malloc(sizeof(int));
*i = 10;
printf("%d", *i);
free(i);
}
void func() {
int *i = new int;
*i = 10;
cout << *i;
delete i;
}
25
References
C C++
void swapint(int *a, int *b) {
int temp;
temp = *a;
*a = *b;
*b = temp;
}
swapint(&i1, &i2);
void swapint(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
swapint(i1, i2);
26
Function Overloading
C C++
int abs(int i);
long labs(long l);
double dabs(double d);
int abs(int i);
long abs(long l);
double abs(double d);
27
Type Inference - 'auto' keyword (C++11)
C C++
int main()
{
int x = 4;
double y = 3.37;
int * ptr = &x;
cout << sizeof(x) << endl
<< sizeof(y) << endl
<< sizeof(ptr) << endl;
return 0;
}
int main()
{
auto x = 4;
auto y = 3.37;
auto ptr = &x;
cout << sizeof(x) << endl
<< sizeof(y) << endl
<< sizeof(ptr) << endl;
return 0;
}
28
Type Inference - 'decltype' keyword (C++11)
C
No equivalent
C++
int fun1() { return 10; }
char fun2() { return 'g'; }
int main() {
// Data type of x is same as return type of fun1()
// and type of y is same as return type of fun2()
decltype(fun1()) x;
decltype(fun2()) y;
cout << typeid(x).name() << endl;
cout << typeid(y).name() << endl;
return 0;
}
29
Classes - Introduction
• The concept of classes, objects, member functions (methods),
and data members.
• Defining a class and creating an object.
• Defining methods (class’s behaviors).
• Declaring data members (class’s attributes).
• Calling methods of an object.
• Differences between data members and local variables of a
function.
• Constructors for initializing an object.
• Separating class’s interface from its implementation.
30
Class vs. Object
• A class is a template for objects
• Classes are the specifications describing objects
• Object holds the data and the actions defining the object
structure and behavior.
31
Class declaration & using
32
class Complex {
public:
double re;
double im;
};
int main()
{
Complex a;
a.re = 1;
a.im = 2;
cout << "(" << a.re << ", " << a.im << ")";
return 0;
}
Object methods (behaviours)
33
class Complex {
public:
void change(double x, double y) {
re = x; im = y;
}
void printOut() {
cout << "(" << re << ", " << im << ")";
}
double re;
double im;
};
int main()
{
Complex a, b;
a.re = 1; a.im = 2;
b.change(a.re + 1, a.im - 3);
a.printOut();
b.printOut();
return 0;
}
Separating methods declaration from definition
34
class Complex {
public:
void change(double x, double y);
void printOut();
double re;
double im;
};
void Complex::change(double x, double y) {
re = x;
im = y;
}
void Complex::printOut() {
cout << "(" << re << ", " << im << ")";
}
Constructor
35
class Complex {
public:
Complex(double x, double y) {
re = x;
im = y;
}
void printOut() {
cout << "(" << re << ", " << im << ")";
}
double re;
double im;
};
int main()
{
Complex a(2,3), b = a;
a.printOut();
b.printOut();
return 0;
}
Separating class’s interface from its implementation
36
// main.cpp file
#include "Complex.h"
int main() {
Complex a(5, 6), b = a;
a.printOut();
b.printOut();
return 0;
}
Preprocessor wrappers
Separating class’s interface from its implementation
37
// Complex.h file
#ifndef COMPLEX_H
#define COMPLEX_H
class Complex {
public:
Complex(double, double);
void printOut();
double re;
double im;
};
#endif
// Complex.cpp file
#include "Complex.h"
#include <iostream>
using namespace std;
Complex::Complex(double x, double y) {
re = x; im = y;
}
void Complex::printOut() {
cout <<"("<<re<<", "<<im<<")";
}
References (Aliases)
38
int main() {
int value = 5;
int * pointer = &value;
int & alias = value;
cout << value << endl;
cout << * pointer << endl;
cout << alias << endl;
return 0;
}
References as function parameters
39
void swapByValue(int, int);
void swapByPointer(int*, int*);
void swapByAlias(int&, int&);
int main() {
int a = 5, b = 7;
cout<<"a = "<<a<<", b = "<<b<<endl;
swapByValue(a, b);
cout<<"a = "<<a<<", b = "<<b<<endl;
swapByPointer(&a, &b);
cout<<"a = "<<a<<", b = "<<b<<endl;
swapByAlias(a, b);
cout<<"a = "<<a<<", b = "<<b<<endl;
return 0;
}
// does not work
void swapByValue(int x, int y)
{
int temp = x;
x = y;
y = temp;
}
void swapByPointer(int* x, int* y)
{
int temp = *x;
*x = *y;
*y = temp;
}
void swapByAlias(int& x, int& y)
{
int temp = x;
x = y;
y = temp;
}
References as return value
40
int maximum(int x, int y) {
return x > y ? x : y;
}
int main() {
int a = 5, b = 7;
cout<<"a = "<<a<<", b = "<<b<<endl;
int c = maximum(a, b);
cout<<"c = "<<c<<endl;
cout<<"maximum(a, b) = "<<maximum(a, b)<<endl;
return 0;
}
References as return value
41
int& maximum(int& x, int& y) {
return x > y ? x : y;
}
int main() {
int a = 5, b = 7;
cout<<"a = "<<a<<", b = "<<b<<endl;
int c = maximum(a, b);
cout<<"c = "<<c<<endl;
cout<<"maximum(a, b) = "<<maximum(a, b)<<endl;
maximum(a, b) = 10;
cout<<"a = "<<a<<", b = "<<b<<endl;
return 0;
}
References as return value
42
int& maximum(int &x, int &y) {
return x > y ? x : y;
}
int main() {
int a = 5, b = 7;
cout<<"a= "<<a<<", b= "<<b<<endl;
cout<<"maximum(a, b)= "<<maximum(a, b)<<endl;
cout<<"&a="<<&a<<", &b="<<&b<<endl;
cout<<"&maximum(a, b)="<<&maximum(a, b)<<endl;
return 0;
}
References as return value
int vals[] = {1, 2, 3, 4, 5};
int& setValues(int i) {
return vals[i];
}
int main () {
cout << "Value before change" << endl;
for (int i = 0; i < 5; i++) {
cout << "vals[" << i << "] = " << vals[i] << endl;
}
setValues(1) = 10;
setValues(3) = 20;
cout << "Value after change" << endl;
for (int i = 0; i < 5; i++) {
cout << "vals[" << i << "] = " << vals[i] << endl;
}
return 0;
}
43
Types of constructors
• Default (zero arguments) constructor
• Parametrized constructor
• Copy constructor
• Move constructor (C++11)
• Conversion constructors (single argument)
• Explicit constructor
44
class Complex {
public:
...
void printOut() {
cout<<"("<<re<<", "<<im<<")"<<endl;
}
private:
double re;
double im;
};
Default constructor
class Complex {
public:
// default constructor
Complex() {
re = 0; im = 0;
}
...
};
int main() {
Complex a;
a.printOut();
return 0;
}
45
Parametrized constructor
46
class Complex {
public:
// parametrized constructor
Complex(double x, double y) {
re = x; im = y;
}
...
};
int main() {
Complex a;
Complex b(1.5, 2.3);
a.printOut();
b.printOut();
return 0;
}
Copy constructor
47
class Complex {
public:
// copy constructor
Complex(Complex& x) {
re = x.re; im = x.im;
}
...
};
int main() {
Complex a;
Complex b(1.5, 2.3);
Complex c = b;
a.printOut();
b.printOut();
c.printOut();
return 0;
}
Conversion constructor (single argument)
48
class Complex {
public:
// conversion constructor
Complex(double x) {
re = x; im = 0;
}
...
};
int main() {
Complex a = 1.5;
Complex b;
b = 5.6;
a.printOut();
b.printOut();
return 0;
}
class Complex {
public:
// conversion constructor
explicit Complex(double x) {
re = x; im = 0;
}
...
};
int main() {
Complex a = 1.5; // does not work
Complex b(1.5); // works
a = 5.6; // does not work
b = Complex(5.6); // works
a.printOut();
b.printOut();
return 0;
}
Explicit conversion constructor
49
Initializing list
50
class Complex {
public:
// default constructor
Complex(): re(0), im(0) {}
// parametrized constructor
Complex(double x, double y): re(x), im(y) {}
// conversion constructor
Complex(double x): re(x), im(0) {}
// copy constructor
Complex(Complex& c): re(c.re), im(c.im) {}
...
};
Destructor
51
class Space {
public:
Space(): sz(1) {
ptr = new int[sz];
cout<<"Creating a Space("<<sz
<<") object"<<endl;
}
Space(int s) : sz(s) {
ptr = new int[sz];
cout<<"Creating a Space("<<sz
<<") object"<<endl;
}
~Space() {
delete[] ptr;
cout<<"Deleting a Space("<<sz
<<") object"<<endl;
}
private:
int * ptr;
const int sz;
};
Space s1;
void fn() {
Space s4(4);
static Space s5(5);
}
int main() {
Space s2(2);
Space s3(3);
fn();
{
Space s6(6);
{
fn();
Space s7(7);
}
}
}
Constructors/Destructors calling order
52
Space s1;
void fn() {
Space s4(4);
static Space s5(5);
}
int main() {
Space s2(2);
Space s3(3);
fn();
{
Space s6(6);
{
fn();
Space s7(7);
}
}
}
Creating a Space(1) object
Creating a Space(2) object
Creating a Space(3) object
Creating a Space(4) object
Creating a Space(5) object
Deleting a Space(4) object
Creating a Space(6) object
Creating a Space(4) object
Deleting a Space(4) object
Creating a Space(7) object
Deleting a Space(7) object
Deleting a Space(6) object
Deleting a Space(3) object
Deleting a Space(2) object
Deleting a Space(5) object
Deleting a Space(1) object
Setters & Getters
53
class Complex {
public:
// Constructors go here
void setRe(double x) { re = x; }
void setIm(double y) { im = y; }
double getRe() { return re; }
double getIm() { return im; }
private:
double re;
double im;
};
int main() {
Complex a(1, 2);
Complex b;
b.setRe(3); b.setIm(5);
cout << a.getRe() << ", " << a.getIm() << endl;
cout << b.getRe() << ", " << b.getIm() << endl;
}
Constant objects and constant methods
54
class Complex {
public:
// Constructors go here
void setRe(double x) { re = x; }
void setIm(double y) { im = y; }
double getRe() { return re; }
double getIm() { return im; }
private:
double re;
double im;
};
int main() {
const Complex a(1, 2);
Complex b;
b.setRe(3); b.setIm(5);
cout << a.getRe() << ", " << a.getIm() << endl; // Error
cout << b.getRe() << ", " << b.getIm() << endl;
}
Constant objects and constant methods
55
class Complex {
public:
// Constructors go here
void setRe(double x) { re = x; }
void setIm(double y) { im = y; }
double getRe() const { return re; }
double getIm() const { return im; }
private:
double re;
double im;
};
int main() {
const Complex a(1, 2);
Complex b;
b.setRe(3); b.setIm(5);
cout << a.getRe() << ", " << a.getIm() << endl; // Works fine now
cout << b.getRe() << ", " << b.getIm() << endl;
}
class Date {
public:
Date(): day(1), month(1), year(1970) { }
Date(int d, int m, int y): day(d), month(m), year(y) { }
void setDay(int d) { day = d; }
void setMonth(int m) { month = m; }
void setYear(int y) { year = y; }
int getDay() const { return day; }
int getMonth() const { return month; }
int getYear() const { return year; }
private:
int day, month, year;
};
class Person {
public:
Person(): name("name"), birthDate(Date()) { }
Person(string n, int d, int m, int y): name(n), birthDate(Date(d, m, y)) { }
Person(string n, Date d): name(n), birthDate(d) { }
string getName() const { return name; }
Date getBirthDate() const { return birthDate; }
private:
string name;
Date birthDate;
};
Hierarchical object composition
56
Hierarchical object composition
57
void printOut(const Date& d) {
cout << d.getDay() << "/"
<< d.getMonth() << "/"
<< d.getYear();
}
void printOut(const Person& p) {
cout << p.getName() << ": ";
printOut(p.getBirthDate());
}
int main() {
Person p1;
Person p2("Youssof", 22, 10, 2015);
Date bd(4,10,2017);
Person p3(“Firas", bd);
printOut(p1); cout << endl;
printOut(p2); cout << endl;
printOut(p3); cout << endl;
return 0;
}
name: 1/1/1970
Youssof: 22/10/2015
Firas: 4/10/2017
Friend functions
58
class Date {
public:
Date(): day(1), month(1), year(1970) { }
Date(int d, int m, int y): day(d), month(m), year(y) { }
void setDay(int d) { day = d; }
void setMonth(int m) { month = m; }
void setYear(int y) { year = y; }
int getDay() const { return day; }
int getMonth() const { return month; }
int getYear() const { return year; }
friend void printOut(const Date& d);
private:
int day, month, year;
};
void printOut(const Date& d) {
cout << d.day << "/"
<< d.month << "/"
<< d.year;
}
Friend functions
59
class Person {
public:
Person(): name("name"), birthDate(Date()) { }
Person(string n, int d, int m, int y): name(n), birthDate(Date(d, m, y)) { }
Person(string n, Date d): name(n), birthDate(d) { }
string getName() const { return name; }
Date getBirthDate() const { return birthDate; }
friend void printOut(const Person& p);
private:
string name;
Date birthDate;
};
void printOut(const Person& p) {
cout << p.name << ": ";
printOut(p.birthDate);
}
Friend classes
60
class Date {
public:
...
friend class Display;
private:
...
};
class Display {
public:
void printOut(const Date& d) {
cout << d.day << "/"
<< d.month << "/"
<< d.year;
}
void printOut(const Person& p) {
cout << p.name << ": ";
printOut(p.birthDate);
}
};
class Person {
public:
...
friend class Display;
private:
...
};
int main() {
Person p1;
Person p2("Youssof", 22, 10, 2015);
Date bd(4,10,2017);
Person p3("Firas", bd);
Display disp;
disp.printOut(p1); cout << endl;
disp.printOut(p2); cout << endl;
disp.printOut(p3); cout << endl;
return 0;
}
Friend class methods
61
class Date;
class Person;
class Display {
public:
void printOut(const Date& d);
void printOut(const Person& p);
};
class Date {
public:
...
friend void Display::printOut(const Date& d);
private:
...
};
class Person {
public:
...
friend void Display::printOut(const Person& p);
private:
...
};
void Display::printOut(const Date& d) {
cout << d.day << "/"
<< d.month << "/"
<< d.year;
}
void Display::printOut(const Person& p) {
cout << p.name << ": ";
printOut(p.birthDate);
}
int main() {
Person p1;
Person p2("Youssof", 22, 10, 2015);
Date bd(4,10,2017);
Person p3("Firas", bd);
Display disp;
disp.printOut(p1); cout << endl;
disp.printOut(p2); cout << endl;
disp.printOut(p3); cout << endl;
return 0;
}
class Complex {
private:
double re, im;
public:
Complex() { re = 0; im = 0; }
Complex(double x, double y) { re = x; im = y; }
void printOut() { cout<<"("<<re<<", "<<im<<")"<<endl; }
};
int main() {
Complex a, b(1,2);
Complex * p1 = new Complex;
Complex * p2 = new Complex(5,8);
a.printOut();
b.printOut();
(*p1).printOut();
p2->printOut();
delete p1;
delete p2;
return 0;
}
Pointers to objects (new & delete operators)
62
class Complex {
private:
double re, im;
public:
Complex() { re = 0; im = 0; }
Complex(double re, double im) { this->re = re; this->im = im; }
void printOut() { cout<<"("<<re<<", "<<im<<")"<<endl; }
};
int main() {
Complex a, b(1,2);
Complex * p1 = new Complex;
Complex * p2 = new Complex(5,8);
a.printOut();
b.printOut();
(*p1).printOut();
p2->printOut();
delete p1;
delete p2;
return 0;
}
Object self-referencing (this keyword)
63
Static data members
64
class Counter {
private:
string name;
int count;
public:
Counter(string n): name(n) {
++count;
cout<<"Object "<<name
<<" is created"<<endl;
}
~Counter() {
--count;
cout<<"Object "<<name
<<" is deleted"<<endl;
}
int getCount() { return count; }
};
int main() {
Counter a("a");
cout<<"There is/are "
<<a.getCount()
<<" Counter object(s) now"<<endl;
Counter b("b");
cout<<"There is/are "
<<b.getCount()
<<" Counter object(s) now"<<endl;
return 0;
}
Static data members
65
class Counter {
private:
string name;
static int count;
public:
Counter(string n): name(n) {
++count;
cout<<"Object "<<name
<<" is created"<<endl;
}
~Counter() {
--count;
cout<<"Object "<<name
<<" is deleted"<<endl;
}
int getCount() { return count; }
};
int Counter::count = 0;
Object a is created
There is/are 1 Counter object(s) now
Object b is created
There is/are 2 Counter object(s) now
Object b is deleted
Object a is deleted
int main() {
Counter a("a");
cout<<"There is/are "
<<a.getCount()
<<" Counter object(s) now"<<endl;
Counter b("b");
cout<<"There is/are "
<<b.getCount()
<<" Counter object(s) now"<<endl;
return 0;
}
Static methods
66
class Counter {
private:
string name;
static int count;
public:
Counter(string n): name(n) {
++count;
cout<<"Object "<<name
<<" is created"<<endl;
}
~Counter() {
--count;
cout<<"Object "<<name
<<" is deleted"<<endl;
}
static int getCount() { return count; }
};
int Counter::count = 0;
Object a is created
There is/are 1 Counter object(s) now
Object b is created
There is/are 2 Counter object(s) now
Object b is deleted
Object a is deleted
int main() {
Counter a("a");
cout<<"There is/are "
<<Counter::getCount()
<<" Counter object(s) now"<<endl;
Counter b("b");
cout<<"There is/are "
<<Counter::getCount()
<<" Counter object(s) now"<<endl;
return 0;
}
Revision over functions
67
int maximum(int a, int b) {
if (a > b)
return a;
else
return b;
}
int maximum(int a, int b, int c) {
if (a > b && a > c)
return a;
else if (b > c)
return b;
else
return c;
}
int maximum(int a, int b) {
return a > b? a : b;
}
int maximum(int a, int b, int c) {
return a>b && a>c? a : (b > c? b : c);
}
int maximum(int a, int b, int c) {
return a>maximum(b,c)? a:maximum(b,c);
}
int maximum(int a, int b, int c) {
return maximum(a, maximum(b,c));
}
Default argument values of functions
68
int sum(int a, int b) {
return a + b;
}
int sum(int a, int b, int c) {
return a + b + c;
}
int sum(int a, int b, int c, int d) {
return a + b + c + d;
}
int main() {
int a = 3, b = 4, c = 5, d = 6;
cout << sum(a, b) << endl;
cout << sum(a, b, c) << endl;
cout << sum(a, b, c, d) << endl;
return 0;
}
int sum(int a, int b, int c=0, int d=0) {
return a + b + c + d;
}
int main() {
int a = 3, b = 4, c = 5, d = 6;
cout << sum(a, b) << endl;
cout << sum(a, b, c) << endl;
cout << sum(a, b, c, d) << endl;
return 0;
}
7
12
18
Default arguments inside classes
69
class Complex {
private:
double re, im;
public:
Complex(double x = 0, double y = 0) : re(x), im(y) {}
...
};
class Complex {
private:
double re, im;
public:
Complex(double=0, double=0);
...
};
Complex::Complex(double x, double y) : re(x), im(y) {}
Some function overloading restrictions
• Function declarations that differ only in the return type are
equivalent.
• Member function declarations with the same name and the
name parameter-type-list cannot be overloaded if any of them
is a static member function declaration.
• Parameter declarations that differ only in a pointer * versus an
array [] are equivalent.
• Parameter declarations that differ only in the presence or
absence of const and/or volatile are equivalent.
• Two parameter declarations that differ only in their default
arguments are equivalent.
70
Recursion
Which one is better?
71
long factorial(int n);
int main() {
cout << factorial(5);
return 0;
}
long factorial(int n) {
long result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
long factorial(int n) {
if (n<=1)
return 1;
return n * factorial(n-1);
}
Recursion
72
int fib(int n) {
if (n <= 1)
return n;
return fib(n-1)+fib(n-2);
}
int main() {
for (int i = 0; i < 10; i++)
cout << fib(i) << endl;
return 0;
}
Operators overloading
73
int main() {
string s1 = "Hello";
string s2 = "world!";
string s3 = s1 + ", " + s2;
cout << s1 << ", " << s2 << endl;
cout << s3 << endl;
return 0;
}
class Complex {
private:
double re, im;
public:
Complex(double x=0, double y=0): re(x), im(y) {}
void print() const {
cout << "(" << re << ", " << im << ")";
}
Complex operator+(const Complex c) {
return Complex(re + c.re, im + c.im);
}
};
int main() {
Complex a(1, 4), b(5, -7);
Complex c = a + b;
cout << "a: "; a.print(); cout << endl;
cout << "b: "; b.print(); cout << endl;
cout << "c: "; c.print(); cout << endl;
return 0;
}
Operator overloading (member function)
74
Complex Complex::operator+(const Complex c) {
return Complex(re + c.re, im + c.im);
}
Operator overloading (non-member function)
With friend functions:
With non-friend functions:
75
class Complex {
private:
...
friend Complex operator+(const Complex c1, const Complex c2);
};
Complex operator+(const Complex c1, const Complex c2) {
return Complex(c1.re + c2.re, c1.im + c2.im);
}
class Complex {
private:
...
// setters & getters
};
Complex operator+ (const Complex c1, const Complex c2) {
return Complex(c1.getRe() + c2.getRe(), c1.getIm() + c2.getIm());
}
Conversion function overloading
• Converts the object into another type
• Member method overloading only
76
class Ratio {
private:
double x, y;
public:
Ratio(double a = 0, double b = 0)
: x(a), y(b) {}
Ratio(const Ratio& c)
: x(c.x), y(c.y) {}
void printOut() {
cout << x << "/" << y;
}
};
class Complex {
private:
double re, im;
public:
Complex(double x = 0, double y = 0)
: re(x), im(y) {}
Complex(const Complex& c)
: re(c.re), im(c.im) {}
void printOut() {
cout<<"("<<re<<", "<<im<<")";
}
operator double() {
return sqrt(re * re + im * im);
}
operator Ratio() {
return Ratio(re, im);
}
operator string() {
stringstream ss;
ss<<"("<<re<<", "<<im<<")";
return ss.str();
}
};
int main() {
Complex c(3.4, 5.6);
c.printOut(); cout << endl;
double d = c;
cout << d << endl;
Ratio r = c;
r.printOut(); cout << endl;
return 0;
}
Pre-/Post-increment/decrement operators
77
class Store {
private:
int value;
public:
Store(int v = 0) : value(v) {}
Store(Store& s) : value(s.value) {}
operator int() {
return value;
}
// pre-increment operator
Store& operator++() {
value++;
return *this;
}
// post-increment operator
Store operator++(int) {
Store copy(*this);
++(*this);
return copy;
}
};
int main() {
Store a(5);
cout << a << endl;
cout << ++a << endl;
cout << a << endl;
cout << a++ << endl;
cout << a << endl;
}
operator++();
Operator overloading restrictions
• Almost any operator can be overloaded in C++. Except:
• member selector – (.)
• scope operator – (::)
• ternary operator – (? :)
• sizeof
• Only built-in operators can be overloaded. New operators can not be created.
• Arity (number of operands) of the operators cannot be changed.
• Precedence and associativity of the operators cannot be changed.
• Overloaded operators cannot have default arguments except the function call operator ()
which can have default arguments.
• Operators cannot be overloaded for built in types only. At least one operand must be used
defined type.
• Assignment (=), subscript ([]), function call (“()”), and member selection (->) operators
must be defined as member functions
• Except the operators specified in the last point, all other operators can be either member
functions or a non member functions.
• Some operators like (assignment)=, (address)& and comma (,) are by default overloaded.
78
C++ operator precedence
79
Precedence Operator Description Associativity
1 :: Scope resolution Left-to-right
2 a++ a-- Suffix/postfix increment and decrement
type() type{} Functional cast
a() Function call
a[] Subscript
. -> Member access
3 ++a --a Prefix increment and decrement Right-to-left
+a -a Unary plus and minus
! ~ Logical NOT and bitwise NOT
(type) C-style cast
*a Indirection (dereference)
&a Address-of
sizeof Size-of[note 1]
co_await await-expression (C++20)
new new[] Dynamic memory allocation
delete delete[] Dynamic memory deallocation
4 .* ->* Pointer-to-member Left-to-right
5 a*b a/b a%b Multiplication, division, and remainder
6 a+b a-b Addition and subtraction
C++ operator precedence
80
Precedence Operator Description Associativity
7 << >> Bitwise left shift and right shift Left-to-right
8 <=> Three-way comparison operator (since C++20)
9 < <= For relational operators < and ≤ respectively
> >= For relational operators > and ≥ respectively
10 == != For relational operators = and ≠ respectively
11 & Bitwise AND
12 ^ Bitwise XOR (exclusive or)
13 | Bitwise OR (inclusive or)
14 && Logical AND
15 || Logical OR
16 a?b:c Ternary conditional[note 2] Right-to-left
throw throw operator
co_yield yield-expression (C++20)
= Direct assignment (provided by default for C++ classes)
+= -= Compound assignment by sum and difference
*= /= %= Compound assignment by product, quotient, and remainder
<<= >>= Compound assignment by bitwise left shift and right shift
&= ^= |= Compound assignment by bitwise AND, XOR, and OR
17 , Comma Left-to-right
OOP concepts: Inheritance
81
class SuperClass {
public:
int superValue;
};
class SubClass : public SuperClass {
public:
int subValue;
};
int main() {
SubClass sub;
sub.subValue = 2;
sub.superValue = 5;
cout << sub.subValue << endl;
cout << sub.superValue << endl;
return 0;
}
Modes of Inheritance
82
class A {
public:
int x;
protected:
int y;
private:
int z;
};
class B : public A {
// x is public
// y is protected
// z is not accessible from B
};
class C : protected A {
// x is protected
// y is protected
// z is not accessible from C
};
// 'private' is default for classes
class D : private A {
// x is private
// y is private
// z is not accessible from D
};
Constructor/Destructor calling order
83
class A {
public:
A() { cout << "A object createdn"; }
~A() { cout << "A object deletedn"; }
};
class B : public A {
public:
B() { cout << "B object createdn"; }
~B() { cout << "B object deletedn"; }
};
class C : public B {
public:
C() { cout << "C object createdn"; }
~C() { cout << "C object deletedn"; }
};
int main() {
A x;
B y;
C z;
return 0;
}
A object created
A object created
B object created
A object created
B object created
C object created
C object deleted
B object deleted
A object deleted
B object deleted
A object deleted
A object deleted
Multiple inheritance
84
class Base {
...
};
class X : public Base {
...
};
class Y : public Base {
...
};
class XY : public X, public Y {
...
};
Multiple inheritance (example)
85
class Vehicle {
public:
Vehicle() {
cout << "This is a Vehiclen";
}
};
class FourWheeler {
public:
FourWheeler() {
cout << "This is a 4-wheeler Vehiclen";
}
};
class Car : public Vehicle, public FourWheeler {
};
int main() {
Car car;
return 0;
}
class A {
public:
A() { cout << "A() constructor is calledn"; }
A(int n) { cout << "A(int) constructor is calledn"; }
~A() { cout << "~A() destructor is calledn"; }
};
class B : public A {
public:
B() { cout << "B() constructor is calledn"; }
B(int n) { cout << "B(int) constructor is calledn"; }
~B() { cout << "~B() destructor is calledn"; }
};
class C : public A {
public:
C() { cout << "C() constructor is calledn"; }
C(int n) { cout << "C(int) constructor is calledn"; }
~C() { cout << "~C() destructor is calledn"; }
};
class D : public B, public C {
public:
D() { cout << "D() constructor is calledn"; }
D(int n) { cout << "D(int) constructor is calledn"; }
~D() { cout << "~D() destructor is calledn"; }
};
int main() {
D x;
D y(10);
return 0;
}
Constructor/Destructor calling order
(multiple-inheritance)
86
A() constructor is called
B() constructor is called
A() constructor is called
C() constructor is called
D() constructor is called
A() constructor is called
B() constructor is called
A() constructor is called
C() constructor is called
D(int) constructor is called
~D() destructor is called
~C() destructor is called
~A() destructor is called
~B() destructor is called
~A() destructor is called
~D() destructor is called
~C() destructor is called
~A() destructor is called
~B() destructor is called
~A() destructor is called
class A {
public:
A() { cout << "A() constructor is calledn"; }
A(int n) { cout << "A(int) constructor is calledn"; }
~A() { cout << "~A() destructor is calledn"; }
};
class B : public A {
public:
B() { cout << "B() constructor is calledn"; }
B(int n) : A(n) { cout << "B(int) constructor is calledn"; }
~B() { cout << "~B() destructor is calledn"; }
};
class C : public A {
public:
C() { cout << "C() constructor is calledn"; }
C(int n) : A(n) { cout << "C(int) constructor is calledn"; }
~C() { cout << "~C() destructor is calledn"; }
};
class D : public B, public C {
public:
D() { cout << "D() constructor is calledn"; }
D(int n) : B(n), C(n) { cout << "D(int) constructor is calledn"; }
~D() { cout << "~D() destructor is calledn"; }
};
int main() {
D x;
D y(10);
return 0;
}
Constructor/Destructor calling order
(calling non-default constructor)
87
A() constructor is called
B() constructor is called
A() constructor is called
C() constructor is called
D() constructor is called
A(int) constructor is called
B(int) constructor is called
A(int) constructor is called
C(int) constructor is called
D(int) constructor is called
~D() destructor is called
~C() destructor is called
~A() destructor is called
~B() destructor is called
~A() destructor is called
~D() destructor is called
~C() destructor is called
~A() destructor is called
~B() destructor is called
~A() destructor is called
Multiple inheritance
The diamond problem
88
Multiple inheritance
The diamond problem
89
class TA : public Faculty, public Student {
public:
TA(int x)
: Student(x), Faculty(x) {
cout << "TA::TA(int) calledn";
}
};
int main() {
TA ta1(30);
}
#include <iostream>
using namespace std;
class Person {
public:
Person(int x) {
cout << "Person::Person(int) calledn";
}
Person() {
cout << "Person::Person() calledn";
}
};
class Faculty : public Person {
public:
Faculty(int x)
: Person(x) {
cout << "Faculty::Faculty(int) calledn";
}
};
class Student : public Person {
public:
Student(int x)
: Person(x) {
cout << "Student::Student(int) calledn";
}
};
Person::Person(int) called
Faculty::Faculty(int) called
Person::Person(int) called
Student::Student(int) called
TA::TA(int) called
Virtual multiple inheritance
90
class Base {
...
};
class X : public Base {
...
};
class Y : public Base {
...
};
class XY : public X, public Y {
...
};
class Base {
...
};
class X : public virtual Base {
...
};
class Y : public virtual Base {
...
};
class XY : public X, public Y {
...
};
Multiple inheritance
The diamond problem
91
class TA : public Faculty, public Student {
public:
TA(int x)
: Student(x), Faculty(x) {
cout << "TA::TA(int) calledn";
}
};
int main() {
TA ta1(30);
}
#include <iostream>
using namespace std;
class Person {
public:
Person(int x) {
cout << "Person::Person(int) calledn";
}
Person() {
cout << "Person::Person() calledn";
}
};
class Faculty : virtual public Person {
public:
Faculty(int x)
: Person(x) {
cout << "Faculty::Faculty(int) calledn";
}
};
class Student : virtual public Person {
public:
Student(int x)
: Person(x) {
cout << "Student::Student(int) calledn";
}
};
Person::Person() called
Faculty::Faculty(int) called
Student::Student(int) called
TA::TA(int) called
Multiple inheritance
The diamond problem
92
class TA : public Faculty, public Student {
public:
TA(int x)
: Student(x), Faculty(x), Person(x) {
cout << "TA::TA(int) calledn";
}
};
int main() {
TA ta1(30);
}
#include <iostream>
using namespace std;
class Person {
public:
Person(int x) {
cout << "Person::Person(int) calledn";
}
Person() {
cout << "Person::Person() calledn";
}
};
class Faculty : virtual public Person {
public:
Faculty(int x)
: Person(x) {
cout << "Faculty::Faculty(int) calledn";
}
};
class Student : virtual public Person {
public:
Student(int x)
: Person(x) {
cout << "Student::Student(int) calledn";
}
};
Person::Person(int) called
Faculty::Faculty(int) called
Student::Student(int) called
TA::TA(int) called
class A {
public:
A() { cout << "A() constructor is calledn"; }
A(int n) { cout << "A(int) constructor is calledn"; }
~A() { cout << "~A() destructor is calledn"; }
};
class B : virtual public A {
public:
B() { cout << "B() constructor is calledn"; }
B(int n) { cout << "B(int) constructor is calledn"; }
~B() { cout << "~B() destructor is calledn"; }
};
class C : virtual public A {
public:
C() { cout << "C() constructor is calledn"; }
C(int n) { cout << "C(int) constructor is calledn"; }
~C() { cout << "~C() destructor is calledn"; }
};
class D : public B, public C {
public:
D() { cout << "D() constructor is calledn"; }
D(int n) { cout << "D(int) constructor is calledn"; }
~D() { cout << "~D() destructor is calledn"; }
};
int main() {
D x;
D y(10);
return 0;
}
Constructor/Destructor calling order
(virtual inheritance)
93
A() constructor is called
B() constructor is called
C() constructor is called
D() constructor is called
A() constructor is called
B() constructor is called
C() constructor is called
D(int) constructor is called
~D() destructor is called
~C() destructor is called
~B() destructor is called
~A() destructor is called
~D() destructor is called
~C() destructor is called
~B() destructor is called
~A() destructor is called
class A {
public:
A() { cout << "A() constructor is calledn"; }
A(int n) { cout << "A(int) constructor is calledn"; }
~A() { cout << "~A() destructor is calledn"; }
};
class B : public virtual A {
public:
B() { cout << "B() constructor is calledn"; }
B(int n) : A(n) { cout << "B(int) constructor is calledn"; }
~B() { cout << "~B() destructor is calledn"; }
};
class C : public virtual A {
public:
C() { cout << "C() constructor is calledn"; }
C(int n) : A(n) { cout << "C(int) constructor is calledn"; }
~C() { cout << "~C() destructor is calledn"; }
};
class D : public B, public C {
public:
D() { cout << "D() constructor is calledn"; }
D(int n) : B(n), C(n) { cout << "D(int) constructor is calledn"; }
~D() { cout << "~D() destructor is calledn"; }
};
int main() {
D x;
D y(10);
return 0;
}
Constructor/Destructor calling order
(virtual inheritance)
94
A() constructor is called
B() constructor is called
C() constructor is called
D() constructor is called
A() constructor is called
B(int) constructor is called
C(int) constructor is called
D(int) constructor is called
~D() destructor is called
~C() destructor is called
~B() destructor is called
~A() destructor is called
~D() destructor is called
~C() destructor is called
~B() destructor is called
~A() destructor is called
class A {
public:
A() { cout << "A() constructor is calledn"; }
A(int n) { cout << "A(int) constructor is calledn"; }
~A() { cout << "~A() destructor is calledn"; }
};
class B : public virtual A {
public:
B() { cout << "B() constructor is calledn"; }
B(int n) : A(n) { cout << "B(int) constructor is calledn"; }
~B() { cout << "~B() destructor is calledn"; }
};
class C : public virtual A {
public:
C() { cout << "C() constructor is calledn"; }
C(int n) : A(n) { cout << "C(int) constructor is calledn"; }
~C() { cout << "~C() destructor is calledn"; }
};
class D : public B, public C {
public:
D() { cout << "D() constructor is calledn"; }
D(int n) : A(n), B(n), C(n) { cout << "D(int) constructor is calledn"; }
~D() { cout << "~D() destructor is calledn"; }
};
int main() {
D x;
D y(10);
return 0;
}
Constructor/Destructor calling order
(virtual inheritance)
95
A() constructor is called
B() constructor is called
C() constructor is called
D() constructor is called
A(int) constructor is called
B(int) constructor is called
C(int) constructor is called
D(int) constructor is called
~D() destructor is called
~C() destructor is called
~B() destructor is called
~A() destructor is called
~D() destructor is called
~C() destructor is called
~B() destructor is called
~A() destructor is called
Multiple inheritance
The ambiguity problem
96
class A {
public:
void doSomething() {...};
};
class B {
public:
void doSomething() {...};
};
class C : public A, public B {
public:
void start() {
// ambiguous call
doSomething();
}
};
Multiple inheritance
The ambiguity problem (solution)
97
class A {
public:
void doSomething() {...};
};
class B {
public:
void doSomething() {...};
};
class C : public A, public B {
public:
void start() {
// correct call
A::doSomething();
}
};
Multiple inheritance
The ambiguity problem
98
class A {
public:
void doSomething() {...};
};
class B {
public:
void doSomething() {...};
};
class C : public A, public B {
public:
void start() {
// correct call
A::doSomething();
}
};
int main() {
C obj;
// ambiguous call
obj.doSomething();
return 0;
}
Multiple inheritance
The ambiguity problem (solution)
99
class A {
public:
void doSomething() {...};
};
class B {
public:
void doSomething() {...};
};
class C : public A, public B {
public:
void start() {
// correct call
A::doSomething();
}
};
int main() {
C obj;
// correct call
obj.A::doSomething();
return 0;
}
Multiple inheritance
The ambiguity problem
100
#include <iostream>
using namespace std;
class A {
public:
int x;
};
class B : public A {
};
class C : public A {
};
class D : public B, public C {
};
int main() {
D obj;
obj.x = 5;
cout << obj.x << "n";
return 0;
}
Multiple inheritance
The ambiguity problem (solution)
101
#include <iostream>
using namespace std;
class A {
public:
int x;
};
class B : public A {
};
class C : public A {
};
class D : public B, public C {
};
int main() {
D obj;
obj.B::x = 5;
obj.C::x = 7;
cout << obj.B::x << "n";
cout << obj.C::x << "n";
return 0;
}
Multiple inheritance
The ambiguity problem (solution)
102
#include <iostream>
using namespace std;
class A {
public:
int x;
};
class B : public virtual A {
};
class C : public virtual A {
};
class D : public B, public C {
};
int main() {
D obj;
obj.B::x = 5;
obj.C::x = 7;
cout << obj.B::x << "n";
cout << obj.C::x << "n";
return 0;
}
class Shape {
protected:
string name;
public:
Shape(string n) : name(n) {
cout << "Shape " << name << " created" << endl;
}
string getName() const { return name; }
};
class Rect : public Shape {
public:
Rect(string n) : Shape(n) {
cout << "Rect " << name << " created" << endl;
}
};
int main() {
Shape sh("First");
Rect r("Second");
cout << "Shape: " << sh.getName() << endl;
cout << "Rect: " << r.getName() << endl;
return 0;
}
Method overriding
103
class Shape {
protected:
string name;
public:
Shape(string n) : name(n) {
cout << "Shape " << name << " created" << endl;
}
void printOut() const { cout << "Shape: "<< name << endl; }
};
class Rect : public Shape {
public:
Rect(string n) : Shape(n) {
cout << "Rect " << name << " created" << endl;
}
void printOut() const { cout << “Rect: "<< name << endl; }
};
int main() {
Shape sh("First");
Rect r("Second");
sh.printOut();
r.printOut();
return 0;
}
Method overriding
104
Polymorphism
105
class Shape {
protected:
...
};
class Rect : public Shape {
...
};
class Triangle : public Shape {
public:
Triangle(string n) : Shape(n) {
cout << "Triangle " << name << " created" << endl;
}
void printOut() const { cout << "Triangle: " << name << endl; }
};
class Circle : public Shape {
public:
Circle(string n) : Shape(n) {
cout << "Circle " << name << " created" << endl;
}
void printOut() const { cout << "Circle: " << name << endl; }
};
Polymorphism (early binding)
106
int main() {
Shape s("s");
Rect r("r");
Triangle t("t");
Circle c("c");
Shape *sh;
sh = &s; sh->printOut();
sh = &r; sh->printOut();
sh = &t; sh->printOut();
sh = &c; sh->printOut();
return 0;
}
Shape s created
Shape r created
Rect r created
Shape t created
Triangle t created
Shape c created
Circle c created
Shape: s
Shape: r
Shape: t
Shape: c
Polymorphism (late binding)
107
int main() {
Shape s("s");
Rect r("r");
Triangle t("t");
Circle c("c");
Shape *sh;
sh = &s; sh->printOut();
sh = &r; sh->printOut();
sh = &t; sh->printOut();
sh = &c; sh->printOut();
return 0;
}
Shape s created
Shape r created
Rect r created
Shape t created
Triangle t created
Shape c created
Circle c created
Shape: s
Rect: r
Triangle: t
Circle: c
class Shape {
...
virtual void printOut() const { cout << "Shape: " << name << endl; }
};
Polymorphism (using references)
108
int main() {
Shape s("s");
Rect r("r");
Triangle t("t");
Circle c("c");
Shape &shS = s;
shS.printOut();
Shape &shR = r;
shR.printOut();
Shape &shT = t;
shT.printOut();
Shape &shC = c;
shC.printOut();
return 0;
}
Rules for Virtual Functions
• Virtual functions cannot be static and cannot be a friend
function of another class.
• Virtual functions should be accessed using pointer or reference
of base class type to achieve run time polymorphism.
• The prototype of virtual functions should be same in base as
well as derived class.
• They are always defined in base class and overridden in
derived class. It is not mandatory for derived class to override
(or re-define the virtual function), in that case base class
version of function is used.
• A class may have virtual destructor, but it cannot have a virtual
constructor.
109
Abstract methods (pure virtual)
110
class Shape {
...
virtual void draw() = 0;
};
class Rect : public Shape {
...
virtual void draw() { cout << "Drawing Rect " << name << endl; };
};
class Triangle : public Shape {
...
virtual void draw() { cout << "Drawing Triangle " << name << endl; };
};
class Circle : public Shape {
...
virtual void draw() { cout << "Drawing Circle " << name << endl; };
};
int main() {
Rect r("r");
Triangle t("t");
Circle c("c");
Shape *sh;
sh = &r; sh->draw();
sh = &t; sh->draw();
sh = &c; sh->draw();
return 0;
}
Abstract vs. Concrete classes
• Any class containing abstract method is abstract
• Inherited abstract method should be implemented in the
subclass or else the subclass becomes abstract
• Abstract classes cannot be instantiated (cannot create objects
of it).
• Pointers to abstract class objects are possible. However, they
should point to concrete object of the class (instances of the
subclasses).
111
Virtual destructor
112
class Shape {
protected:
string name;
public:
Shape(string n="unknown") : name(n) {
cout << "Shape " << name << " created" << endl;
}
~Shape() {
cout << "Shape " << name << " destroyed" << endl;
}
virtual void printOut() const { cout << "Shape: " << name << endl; }
virtual void draw() = 0;
};
class Rect : public Shape {
public:
Rect(string n) : Shape(n) {
cout << "Rect " << name << " created" << endl;
}
~Rect() {
cout << "Rect " << name << " destroyed" << endl;
}
void printOut() const { cout << "Rect: " << name << endl; }
virtual void draw() { cout << "Drawing Rect " << name << endl; };
};
Virtual destructor
113
void printShape(Shape *s) {
s->printOut();
}
void drawShape(Shape *s) {
s->draw();
}
int main() {
Rect r("r");
Triangle t("t");
printShape(&r);
drawShape(&r);
printShape(&t);
drawShape(&t);
return 0;
}
Shape r created
Rect r created
Shape t created
Triangle t created
Rect: r
Drawing Rect r
Triangle: t
Drawing Triangle t
Triangle t destroyed
Shape t destroyed
Rect r destroyed
Shape r destroyed
Virtual destructor
114
int main() {
Shape *sh;
sh = new Rect("r");
printShape(sh);
drawShape(sh);
delete sh;
sh = new Triangle("t");
printShape(sh);
drawShape(sh);
delete sh;
return 0;
}
Shape r created
Rect r created
Rect: r
Drawing Rect r
Shape r destroyed
Shape t created
Triangle t created
Triangle: t
Drawing Triangle t
Shape t destroyed
class Shape {
...
virtual ~Shape() {
cout << "Shape " << name << " destroyed" << endl;
}
...
};
int main() {
Shape *sh;
sh = new Rect("r");
printShape(sh);
drawShape(sh);
delete sh;
sh = new Triangle("t");
printShape(sh);
drawShape(sh);
delete sh;
return 0;
}
Virtual destructor
115
Shape r created
Rect r created
Rect: r
Drawing Rect r
Rect r destroyed
Shape r destroyed
Shape t created
Triangle t created
Triangle: t
Drawing Triangle t
Triangle t destroyed
Shape t destroyed
Anonymous object
116
int main() {
Rect r("r");
Triangle *t = new Triangle("t");
Triangle *p = t;
delete t;
return 0;
}
Shape r created
Rect r created
Shape t created
Triangle t created
Triangle t destroyed
Shape t destroyed
Rect r destroyed
Shape r destroyed
class Button {
protected:
string label;
public:
Button(string l="unlabel") : label(l) {
cout << "Button " << label << " created" << endl;
}
virtual ~Button() {
cout << "Button " << label << " destroyed" << endl;
}
virtual void onClick() = 0;
};
int main() {
class : public Button {
public:
virtual void onClick() { cout << "Save button clicked" << endl; }
void setLabel(string l) { label = l; }
} saveBtn;
saveBtn.setLabel("Save");
saveBtn.onClick();
return 0;
}
Anonymous class
117
Templates
118
int maximum(int a, int b) {
return a > b? a : b;
}
int maximum(double a, double b) {
return a > b? a : b;
}
int sum(int a, int b, int c, int d) {
return a + b + c + d;
}
double sum(double a, double b, double c, double d) {
return a + b + c + d;
}
Function template
119
template <class T>
T maximum(T a, T b) {
return a > b? a : b;
}
template <typename T>
T sum(T a, T b, T c, T d) {
return a + b + c + d;
}
int main() {
cout << maximum(1, 4) << endl;
cout << maximum(1.2, 4.5) << endl;
// cout << maximum(5.3, 2) << endl; does not work
cout << maximum<double>(5.3, 2) << endl; // This works
cout << sum(1, 2, 3, 4) << endl;
cout << sum(1.2, 2.3, 3.4, 4.5) << endl;
return 0;
}
Function template specialization
120
template <class T>
void fun(T a) {
cout << "Main fun() template: " << a << endl;
}
template<>
void fun(double a) {
cout << "double fun() template: " << a << endl;
}
int main()
{
fun(1);
fun(3.14);
fun("Hello");
return 0;
}
Main fun() template: 1
Main fun() template: 3.14
Main fun() template: Hello
Main fun() template: 1
double fun() template: 3.14
Main fun() template: Hello
Class templates
121
template <class T>
class Stack {
private:
T elems[10]; // elements
public:
void push(T const &); // push element
T pop(); // pop element
bool empty() const { // return true if empty.
...
}
};
template <class T>
void Stack<T>::push(T const &elem) {
// append copy of passed element
}
template <class T>
T Stack<T>::pop() {
// remove last element
}
int main() {
Stack<int> intStack; // stack of ints
Stack<string> stringStack; // stack of strings
// manipulate int stack
intStack.push(7);
cout << intStack.pop() << endl;
// manipulate string stack
stringStack.push("hello");
cout << stringStack.pop() << endl;
return 0;
}
Class templates specialization
122
template <class T>
class Stack {
private:
T elems[10]; // elements
public:
void push(T const &); // push element
T pop(); // pop element
bool empty() const { // return true if empty.
...
}
};
template <>
class Stack<string> {
...
};
Class templates with default type
123
template <class T = double>
class Stack {
private:
T elems[10]; // elements
public:
void push(T const &); // push element
T pop(); // pop element
bool empty() const { // return true if empty.
...
}
};
int main() {
Stack<int> intStack; // stack of ints
Stack<> doubleStack; // stack of doubles
// manipulate int stack
intStack.push(7);
cout << intStack.pop() << endl;
// manipulate double stack
doubleStack.push(3.14);
cout << doubleStack.pop() << endl;
return 0;
}
Class templates with nontype parameters
124
template <class T, int sSize>
class Stack {
private:
T elems[sSize]; // elements
public:
void push(T const &); // push element
T pop(); // pop element
bool empty() const { // return true if empty.
...
}
};
template <class T, int sSize>
void Stack<T,sSize>::push(T const &elem) {
// append copy of passed element
}
template <class T, int sSize>
T Stack<T,sSize>::pop() {
// remove last element
}
int main() {
Stack<int, 10> intStack;
Stack<string, 20> stringStack;
// manipulate int stack
intStack.push(7);
cout << intStack.pop() << endl;
// manipulate string stack
stringStack.push("hello");
cout << stringStack.pop() << endl;
return 0;
}
Class templates with default type
125
template <class T = double>
class Stack {
...
};
int main() {
// stack of ints
Stack<int> intStack;
// stack of doubles
Stack<> doubleStack;
...
return 0;
}
template <class T=double, int sSize=30>
class Stack {
...
};
int main() {
// stack of 10 ints
Stack<int, 10> intStack;
// stack of 30 strings
Stack<string> stringStack;
// stack of 30 doubles
Stack<> doubleStack;
...
return 0;
}
class Date {
private:
int day, month, year;
public:
Date(int d=11, int m=11, int y=1975);
void printOut();
friend ostream& operator<<(ostream& os, const Date& dt);
friend istream& operator>> (istream& is, Date& dt);
};
Date::Date(int d, int m, int y)
: day(d<1?1:d>31?31:d)
, month(m<1?1:m>12?12:m)
, year(y<0?-y:y) {}
void Date::printOut() {
cout << day << "/" << month << "/" << year;
}
ostream& operator<<(ostream& os, const Date& dt) {
os << dt.day << "/" << dt.month << "/" << dt.year;
return os;
}
istream& operator>> (istream& is, Date& dt) {
is >> dt.day >> dt.month >> dt.year;
return is;
}
Overloading output/input streams
126
int main() {
Date d1, d2(11, 12, 2019);
d1.printOut(); cout << endl;
d2.printOut(); cout << endl;
cin >> d2;
cout << d1 << endl;
cout << d2 << endl;
return 0;
}
Sorting Algorithms
• Bubble sort
• Selection sort
• Insertion sort
• Quick sort
• Merge Sort
• Heap Sort
• Radix Sort
• Counting Sort
• Bucket Sort
• ShellSort
127
void swap(int &x, int &y) {
int temp = x;
x = y;
y = temp;
}
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
...
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);
printArray(arr, n);
methodOfSort(arr, n);
cout << "Sorted array: n";
printArray(arr, n);
return 0;
}
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++)
for (int j = 0; j < n - i - 1; j++)
if (arr[j] > arr[j + 1])
swap(arr[j], arr[j + 1]);
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
printArray(arr, n);
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
cout << "Sorted array: n";
printArray(arr, n);
return 0;
}
Bubble Sort
128
Selection Sort
129
void selectionSort(int arr[], int n) {
int min_idx;
for (int i = 0; i < n - 1; i++) {
min_idx = i;
for (int j = i + 1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
swap(arr[min_idx], arr[i]);
}
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
printArray(arr, n);
int n = sizeof(arr) / sizeof(arr[0]);
selectionSort(arr, n);
cout << "Sorted array: n";
printArray(arr, n);
return 0;
}
Insertion Sort
130
void insertionSort(int arr[], int n) {
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
printArray(arr, n);
int n = sizeof(arr) / sizeof(arr[0]);
insertionSort(arr, n);
cout << "Sorted array: n";
printArray(arr, n);
return 0;
}
Quick Sort
131
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = (low - 1);
for (int j = low; j <= high - 1; j++) {
if (arr[j] <= pivot) {
i++;
swap(arr[i], arr[j]);
}
}
swap(arr[i + 1], arr[high]);
return (i + 1);
}
void quickSort(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
printArray(arr, n);
int n = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, n-1);
cout << "Sorted array: n";
printArray(arr, n);
return 0;
}
Standard Template Library (STL)
• A set of C++ template classes to provide common
programming data structures and functions such as lists,
stacks, arrays, etc.
• STL has four components:
• Containers
• Algorithms
• Functions (Functors)
• Iterators
132
STL Containers
• A container is a holder object that stores a collection of other objects (its
elements).
• The container manages the storage space for its elements and provides member
functions to access them, either directly or through iterators.
• Containers replicate structures very commonly used in programming: dynamic
arrays (vector), queues (queue), stacks (stack), heaps (priority_queue), linked
lists (list), trees (set), associative arrays (map)…
• Many containers have several member functions in common, and share
functionalities. The decision of which type of container to use for a specific need
does not generally depend only on the functionality offered by the container, but
also on the efficiency of some of its members (complexity).
• stack, queue and priority_queue are implemented as container adaptors.
Container adaptors are not full container classes, but classes that provide a
specific interface relying on an object of one of the container classes (such as
deque or list) to handle the elements. The underlying container is encapsulated
in such a way that its elements are accessed by the members of the container
adaptor independently of the underlying container class used.
133
STL Container class templates
• Sequence containers:
• array (C++11): Array class (class template)
• vector: Vector (class template)
• deque: Double ended queue (class template)
• forward_list (C++11): Forward list (class template)
• list: List (class template)
• Container adaptors:
• stack: LIFO stack (class template)
• queue: FIFO queue (class template)
• priority_queue: Priority queue (class template)
134
STL Container class templates
• Associative containers:
• set: Set (class template)
• multiset: Multiple-key set (class template)
• map: Map (class template)
• multimap: Multiple-key map (class template)
• Unordered associative containers:
• unordered_set (C++11): Unordered Set (class template)
• unordered_multiset (C++11): Unordered Multiset (class template)
• unordered_map (C++11): Unordered Map (class template)
• unordered_multimap (C++11): Unordered Multimap (class template)
135
STL Algorithms <algorithm>
• Non-modifying sequence operations:
• all_of : Test condition on all elements in range (function template)
• any_of : Test if any element in range fulfills condition (function
template)
• none_of : Test if no elements fulfill condition (function template)
• for_each: Apply function to range (function template)
• find: Find value in range (function template)
• find_if: Find element in range (function template)
• find_if_not: Find element in range (negative condition) (function
template)
• find_end: Find last subsequence in range (function template)
• find_first_of: Find element from set in range (function template)
• adjacent_find: Find equal adjacent elements in range (function
template)
136
STL Algorithms <algorithm>
• Non-modifying sequence operations:
• count: Count appearances of value in range (function template)
• count_if: Return number of elements in range satisfying condition
(function template)
• mismatch: Return first position where two ranges differ (function
template)
• equal: Test whether the elements in two ranges are equal (function
template)
• is_permutation: Test whether range is permutation of another (function
template)
• search: Search range for subsequence (function template)
• search_n: Search range for elements (function template)
137
STL Algorithms <algorithm>
• Modifying sequence operations:
• copy: Copy range of elements (function template)
• copy_n: Copy elements (function template)
• copy_if: Copy certain elements of range (function template)
• copy_backward: Copy range of elements backward (function template)
• move: Move range of elements (function template)
• move_backward: Move range of elements backward (function template)
• swap: Exchange values of two objects (function template)
• swap_ranges: Exchange values of two ranges (function template)
• iter_swap: Exchange values of objects pointed to by two iterators
(function template)
• transform: Transform range (function template)
138
STL Algorithms <algorithm>
• Modifying sequence operations:
• replace: Replace value in range (function template)
• replace_if: Replace values in range (function template)
• replace_copy: Copy range replacing value (function template)
• replace_copy_if: Copy range replacing value (function template)
• fill: Fill range with value (function template)
• fill_n: Fill sequence with value (function template)
• generate: Generate values for range with function (function template)
• generate_n: Generate values for sequence with function (function
template)
• remove: Remove value from range (function template)
• remove_if: Remove elements from range (function template)
• remove_copy: Copy range removing value (function template)
• remove_copy_if: Copy range removing values (function template)
139
STL Algorithms <algorithm>
• Modifying sequence operations:
• unique: Remove consecutive duplicates in range (function template)
• unique_copy: Copy range removing duplicates (function template)
• reverse: Reverse range (function template)
• reverse_copy: Copy range reversed (function template)
• rotate: Rotate left the elements in range (function template)
• rotate_copy: Copy range rotated left (function template)
• random_shuffle: Randomly rearrange elements in range (function
template)
• shuffle: Randomly rearrange elements in range using generator
(function template)
140
STL Algorithms <algorithm>
• Partitions:
• is_partitioned: Test whether range is partitioned (function template)
• partition: Partition range in two (function template)
• stable_partition: Partition range in two - stable ordering (function
template)
• partition_copy: Partition range into two (function template)
• partition_point: Get partition point (function template)
141
STL Algorithms <algorithm>
• Sorting:
• sort: Sort elements in range (function template)
• stable_sort: Sort elements preserving order of equivalents (function
template)
• partial_sort: Partially sort elements in range (function template)
• partial_sort_copy: Copy and partially sort range (function template)
• is_sorted: Check whether range is sorted (function template)
• is_sorted_until: Find first unsorted element in range (function template)
• nth_element: Sort element in range (function template)
142
STL Algorithms <algorithm>
• Sorting:
• sort: Sort elements in range (function template)
• stable_sort: Sort elements preserving order of equivalents (function
template)
• partial_sort: Partially sort elements in range (function template)
• partial_sort_copy: Copy and partially sort range (function template)
• is_sorted: Check whether range is sorted (function template)
• is_sorted_until: Find first unsorted element in range (function template)
• nth_element: Sort element in range (function template)
143
STL Algorithms <algorithm>
• Binary search (operating on partitioned/sorted ranges):
• lower_bound: Return iterator to lower bound (function template)
• upper_bound: Return iterator to upper bound (function template)
• equal_range: Get subrange of equal elements (function template)
• binary_search: Test if value exists in sorted sequence (function
template)
144
STL Algorithms <algorithm>
• Merge (operating on sorted ranges):
• merge: Merge sorted ranges (function template)
• inplace_merge: Merge consecutive sorted ranges (function template)
• includes: Test whether sorted range includes another sorted range
(function template)
• set_union: Union of two sorted ranges (function template)
• set_intersection: Intersection of two sorted ranges (function template)
• set_difference: Difference of two sorted ranges (function template)
• set_symmetric_difference: Symmetric difference of two sorted ranges
(function template)
145
STL Algorithms <algorithm>
• Heap:
• push_heap: Push element into heap range (function template)
• pop_heap: Pop element from heap range (function template)
• make_heap: Make heap from range (function template)
• sort_heap: Sort elements of heap (function template)
• is_heap: Test if range is heap (function template)
• is_heap_until: Find first element not in heap order (function template)
146
STL Algorithms <algorithm>
• Min/max:
• min: Return the smallest (function template)
• max: Return the largest (function template)
• minmax: Return smallest and largest elements (function template)
• min_element: Return smallest element in range (function template)
• max_element: Return largest element in range (function template)
• minmax_element: Return smallest and largest elements in range (function
template)
• Other:
• lexicographical_compare: Lexicographical less-than comparison (function
template)
• next_permutation: Transform range to next permutation (function
template)
• prev_permutation: Transform range to previous permutation (function
template)
147

More Related Content

Similar to C++ lectures all chapters in one slide.pptx

Cs1123 8 functions
Cs1123 8 functionsCs1123 8 functions
Cs1123 8 functionsTAlha MAlik
 
C aptitude scribd
C aptitude scribdC aptitude scribd
C aptitude scribdAmit Kapoor
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Mario Fusco
 
Computer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paperComputer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paperDeepak Singh
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorJussi Pohjolainen
 
2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2Warui Maina
 
C++ 11 Features
C++ 11 FeaturesC++ 11 Features
C++ 11 FeaturesJan Rüegg
 
54602399 c-examples-51-to-108-programe-ee01083101
54602399 c-examples-51-to-108-programe-ee0108310154602399 c-examples-51-to-108-programe-ee01083101
54602399 c-examples-51-to-108-programe-ee01083101premrings
 
C aptitude.2doc
C aptitude.2docC aptitude.2doc
C aptitude.2docSrikanth
 
Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4Ismar Silveira
 

Similar to C++ lectures all chapters in one slide.pptx (20)

Cs1123 8 functions
Cs1123 8 functionsCs1123 8 functions
Cs1123 8 functions
 
C aptitude scribd
C aptitude scribdC aptitude scribd
C aptitude scribd
 
Advanced C - Part 2
Advanced C - Part 2Advanced C - Part 2
Advanced C - Part 2
 
Lecture 3 c++
Lecture 3 c++Lecture 3 c++
Lecture 3 c++
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
Oop1
Oop1Oop1
Oop1
 
Computer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paperComputer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paper
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operator
 
C++ file
C++ fileC++ file
C++ file
 
DataTypes.ppt
DataTypes.pptDataTypes.ppt
DataTypes.ppt
 
2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2
 
12
1212
12
 
C++ 11 Features
C++ 11 FeaturesC++ 11 Features
C++ 11 Features
 
54602399 c-examples-51-to-108-programe-ee01083101
54602399 c-examples-51-to-108-programe-ee0108310154602399 c-examples-51-to-108-programe-ee01083101
54602399 c-examples-51-to-108-programe-ee01083101
 
C aptitude.2doc
C aptitude.2docC aptitude.2doc
C aptitude.2doc
 
Captitude 2doc-100627004318-phpapp01
Captitude 2doc-100627004318-phpapp01Captitude 2doc-100627004318-phpapp01
Captitude 2doc-100627004318-phpapp01
 
C++ practical
C++ practicalC++ practical
C++ practical
 
Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4
 
C++ file
C++ fileC++ file
C++ file
 
C++ file
C++ fileC++ file
C++ file
 

Recently uploaded

Book Review of Run For Your Life Powerpoint
Book Review of Run For Your Life PowerpointBook Review of Run For Your Life Powerpoint
Book Review of Run For Your Life Powerpoint23600690
 
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading RoomSternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading RoomSean M. Fox
 
How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17Celine George
 
Basic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of TransportBasic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of TransportDenish Jangid
 
MOOD STABLIZERS DRUGS.pptx
MOOD     STABLIZERS           DRUGS.pptxMOOD     STABLIZERS           DRUGS.pptx
MOOD STABLIZERS DRUGS.pptxPoojaSen20
 
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...Nguyen Thanh Tu Collection
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...Nguyen Thanh Tu Collection
 
Observing-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxObserving-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxAdelaideRefugio
 
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptxAnalyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptxLimon Prince
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文中 央社
 
e-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopale-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi RajagopalEADTU
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptNishitharanjan Rout
 
An Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge AppAn Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge AppCeline George
 
An overview of the various scriptures in Hinduism
An overview of the various scriptures in HinduismAn overview of the various scriptures in Hinduism
An overview of the various scriptures in HinduismDabee Kamal
 
SPLICE Working Group: Reusable Code Examples
SPLICE Working Group:Reusable Code ExamplesSPLICE Working Group:Reusable Code Examples
SPLICE Working Group: Reusable Code ExamplesPeter Brusilovsky
 
UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024Borja Sotomayor
 

Recently uploaded (20)

Book Review of Run For Your Life Powerpoint
Book Review of Run For Your Life PowerpointBook Review of Run For Your Life Powerpoint
Book Review of Run For Your Life Powerpoint
 
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading RoomSternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
 
How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17
 
Basic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of TransportBasic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of Transport
 
MOOD STABLIZERS DRUGS.pptx
MOOD     STABLIZERS           DRUGS.pptxMOOD     STABLIZERS           DRUGS.pptx
MOOD STABLIZERS DRUGS.pptx
 
OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...
 
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
 
Supporting Newcomer Multilingual Learners
Supporting Newcomer  Multilingual LearnersSupporting Newcomer  Multilingual Learners
Supporting Newcomer Multilingual Learners
 
Observing-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxObserving-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptx
 
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptxAnalyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
 
e-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopale-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopal
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.ppt
 
Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"
 
An Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge AppAn Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge App
 
Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"
 
An overview of the various scriptures in Hinduism
An overview of the various scriptures in HinduismAn overview of the various scriptures in Hinduism
An overview of the various scriptures in Hinduism
 
SPLICE Working Group: Reusable Code Examples
SPLICE Working Group:Reusable Code ExamplesSPLICE Working Group:Reusable Code Examples
SPLICE Working Group: Reusable Code Examples
 
UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024
 

C++ lectures all chapters in one slide.pptx

  • 1. Computer Programming II – C++ Introduction to C++
  • 2. C++ as a better C • Created by Bjarne Stroustrup in 1979 to bring Object-Oriented Programming (OOP) support to C language. • First “C with classes” compiler called “Cfront” derived from C compiler called “CPre”. • “C++” name change in 1983 with new features added like virtual functions, function overloading, references with the & symbol, the const keyword, and single- line comments. • Language updated again in 1989 to include protected and static members, as well as multiple inheritance. • In 1998, the C++ standards committee published the first international standard for C++ known as “C++98” with STL. • http://www.trytoprogram.com/cplusplu s-programming/history/ 2
  • 5. Integer & real number literals Type Example Octal 0123 Hexadecimal 0x5B1F int 123 unsigned int 123u long 123l unsigned long 123ul float 123.45f double 123.45 5
  • 6. Boolean, Character & string literals 6 A value of true representing true. A value of false representing false. Character literals are surrounded by single quotations 'x’. String literals are surrounded by single quotations "Hello".
  • 8. The if statement if (condition) statement; if (x == 100) cout << "x is 100"; if (x == 100) cout << "x is 100"; if (x == 100) { cout << "x is "; cout << x; } if (x == 100) { cout << "x is "; cout << x;} 8
  • 9. The if-else statement if (condition) statement; else statement; if (x == 100) cout << "x is 100"; else cout << "x is not 100"; if (x > 0) cout << "x is positive"; else if (x < 0) cout << "x is negative"; else cout << "x is 0"; 9
  • 10. The ?: operator Condition? expr-if-true : expr-if-false; cout << (x == 100? "x is 100":"x is not 100"); y = x > 100? 5 : 4; int min(int a, int b) { return a < b? a : b; } 10
  • 11. The switch statement switch (expression) { case constant1: statements-group-1; break; case constant2: statements-group-2; break; . . . default: default-statements-group; } 11
  • 12. The switch statement switch (x) { case 1: cout << "x is 1"; break; case 2: cout << "x is 2"; break; default: cout << "value of x unknown"; } switch (x) { case 1: case 2: case 3: cout << "x is 1, 2 or 3"; break; default: cout << "x is not 1, 2 nor 3"; } 12
  • 13. The while statement while (expression) statement; int main () { int n = 10; while (n>0) { cout << n << ", "; --n; } cout << "liftoff!n"; } 13
  • 14. The do-while statement do statement while (expression); int main () { string str; do { cout << "Enter text: "; getline (cin, str); cout << "You entered: " << str << 'n'; } while (str != "goodbye"); } 14
  • 15. The for.. statement for (initialization; condition; increase) statement; int main () { for (int n=10; n>0; n--) { cout << n << ", "; } cout << "liftoff!n"; } 15
  • 16. The for each statement (C++11) for (declaration : range) statement; int main () { string str {"Hello!"}; for (char c : str) { cout << "[" << c << "]"; } cout << 'n'; } 16
  • 17. The goto statement (avoid!) goto label; … label: statement; LOOP:do { if(a == 15) { // skip the iteration. a = a + 1; goto LOOP; } cout << "value of a: " << a << endl; a = a + 1; } while(a < 20); 17
  • 18. The continue statement continue; do { if(a == 15) { // skip the iteration. a = a + 1; continue; } cout << "value of a: " << a << endl; a = a + 1; } while(a < 20) 18
  • 19. The break statement break; do { cout << "value of a: " << a << endl; a = a + 1; if(a > 15) { // terminate the loop break; } } while(a < 20); 19
  • 21. Casts C C++ int i = 0; long l = (long) i; int i = 0; long l = long(i); 21
  • 22. Flexible Declarations C C++ void makeit(void) { int i; char *cp; /* imagine 2000 lines of code here */ /* allocate 100 bytes for cp */ /* 1st use of cp */ cp = malloc(100); /* 1st use of i */ for (i = 0; i<100; ++i) { /* do something */ } /* more code */ } void makeit(void) { // 2000 lines of code char *cp = new char[100]; for (int i = 0; i<100; ++i) { /* do something */ } /* more code */ } 22
  • 23. 'struct' and 'union' Tags C C++ struct foo { int a; float b; } struct foo f; typedef struct { int a; float b; } foo; foo f; struct foo { int a; float b; } foo f; 23
  • 24. The :: Operator C C++ int a = 2; int main() { int a = 5; cout << a << endl; cout << ::a << endl; } int a = 2; int main() { int a = 5; cout << a << endl; /* Cannot access global variable (a) */ } int x = 11; void f4() { int y = x; // global x int x = 22; y = x; // local x } 24
  • 25. 'new' and 'delete' C C++ void func(void) { int *i; i = (int *) malloc(sizeof(int)); *i = 10; printf("%d", *i); free(i); } void func() { int *i = new int; *i = 10; cout << *i; delete i; } 25
  • 26. References C C++ void swapint(int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; } swapint(&i1, &i2); void swapint(int &a, int &b) { int temp = a; a = b; b = temp; } swapint(i1, i2); 26
  • 27. Function Overloading C C++ int abs(int i); long labs(long l); double dabs(double d); int abs(int i); long abs(long l); double abs(double d); 27
  • 28. Type Inference - 'auto' keyword (C++11) C C++ int main() { int x = 4; double y = 3.37; int * ptr = &x; cout << sizeof(x) << endl << sizeof(y) << endl << sizeof(ptr) << endl; return 0; } int main() { auto x = 4; auto y = 3.37; auto ptr = &x; cout << sizeof(x) << endl << sizeof(y) << endl << sizeof(ptr) << endl; return 0; } 28
  • 29. Type Inference - 'decltype' keyword (C++11) C No equivalent C++ int fun1() { return 10; } char fun2() { return 'g'; } int main() { // Data type of x is same as return type of fun1() // and type of y is same as return type of fun2() decltype(fun1()) x; decltype(fun2()) y; cout << typeid(x).name() << endl; cout << typeid(y).name() << endl; return 0; } 29
  • 30. Classes - Introduction • The concept of classes, objects, member functions (methods), and data members. • Defining a class and creating an object. • Defining methods (class’s behaviors). • Declaring data members (class’s attributes). • Calling methods of an object. • Differences between data members and local variables of a function. • Constructors for initializing an object. • Separating class’s interface from its implementation. 30
  • 31. Class vs. Object • A class is a template for objects • Classes are the specifications describing objects • Object holds the data and the actions defining the object structure and behavior. 31
  • 32. Class declaration & using 32 class Complex { public: double re; double im; }; int main() { Complex a; a.re = 1; a.im = 2; cout << "(" << a.re << ", " << a.im << ")"; return 0; }
  • 33. Object methods (behaviours) 33 class Complex { public: void change(double x, double y) { re = x; im = y; } void printOut() { cout << "(" << re << ", " << im << ")"; } double re; double im; }; int main() { Complex a, b; a.re = 1; a.im = 2; b.change(a.re + 1, a.im - 3); a.printOut(); b.printOut(); return 0; }
  • 34. Separating methods declaration from definition 34 class Complex { public: void change(double x, double y); void printOut(); double re; double im; }; void Complex::change(double x, double y) { re = x; im = y; } void Complex::printOut() { cout << "(" << re << ", " << im << ")"; }
  • 35. Constructor 35 class Complex { public: Complex(double x, double y) { re = x; im = y; } void printOut() { cout << "(" << re << ", " << im << ")"; } double re; double im; }; int main() { Complex a(2,3), b = a; a.printOut(); b.printOut(); return 0; }
  • 36. Separating class’s interface from its implementation 36 // main.cpp file #include "Complex.h" int main() { Complex a(5, 6), b = a; a.printOut(); b.printOut(); return 0; }
  • 37. Preprocessor wrappers Separating class’s interface from its implementation 37 // Complex.h file #ifndef COMPLEX_H #define COMPLEX_H class Complex { public: Complex(double, double); void printOut(); double re; double im; }; #endif // Complex.cpp file #include "Complex.h" #include <iostream> using namespace std; Complex::Complex(double x, double y) { re = x; im = y; } void Complex::printOut() { cout <<"("<<re<<", "<<im<<")"; }
  • 38. References (Aliases) 38 int main() { int value = 5; int * pointer = &value; int & alias = value; cout << value << endl; cout << * pointer << endl; cout << alias << endl; return 0; }
  • 39. References as function parameters 39 void swapByValue(int, int); void swapByPointer(int*, int*); void swapByAlias(int&, int&); int main() { int a = 5, b = 7; cout<<"a = "<<a<<", b = "<<b<<endl; swapByValue(a, b); cout<<"a = "<<a<<", b = "<<b<<endl; swapByPointer(&a, &b); cout<<"a = "<<a<<", b = "<<b<<endl; swapByAlias(a, b); cout<<"a = "<<a<<", b = "<<b<<endl; return 0; } // does not work void swapByValue(int x, int y) { int temp = x; x = y; y = temp; } void swapByPointer(int* x, int* y) { int temp = *x; *x = *y; *y = temp; } void swapByAlias(int& x, int& y) { int temp = x; x = y; y = temp; }
  • 40. References as return value 40 int maximum(int x, int y) { return x > y ? x : y; } int main() { int a = 5, b = 7; cout<<"a = "<<a<<", b = "<<b<<endl; int c = maximum(a, b); cout<<"c = "<<c<<endl; cout<<"maximum(a, b) = "<<maximum(a, b)<<endl; return 0; }
  • 41. References as return value 41 int& maximum(int& x, int& y) { return x > y ? x : y; } int main() { int a = 5, b = 7; cout<<"a = "<<a<<", b = "<<b<<endl; int c = maximum(a, b); cout<<"c = "<<c<<endl; cout<<"maximum(a, b) = "<<maximum(a, b)<<endl; maximum(a, b) = 10; cout<<"a = "<<a<<", b = "<<b<<endl; return 0; }
  • 42. References as return value 42 int& maximum(int &x, int &y) { return x > y ? x : y; } int main() { int a = 5, b = 7; cout<<"a= "<<a<<", b= "<<b<<endl; cout<<"maximum(a, b)= "<<maximum(a, b)<<endl; cout<<"&a="<<&a<<", &b="<<&b<<endl; cout<<"&maximum(a, b)="<<&maximum(a, b)<<endl; return 0; }
  • 43. References as return value int vals[] = {1, 2, 3, 4, 5}; int& setValues(int i) { return vals[i]; } int main () { cout << "Value before change" << endl; for (int i = 0; i < 5; i++) { cout << "vals[" << i << "] = " << vals[i] << endl; } setValues(1) = 10; setValues(3) = 20; cout << "Value after change" << endl; for (int i = 0; i < 5; i++) { cout << "vals[" << i << "] = " << vals[i] << endl; } return 0; } 43
  • 44. Types of constructors • Default (zero arguments) constructor • Parametrized constructor • Copy constructor • Move constructor (C++11) • Conversion constructors (single argument) • Explicit constructor 44 class Complex { public: ... void printOut() { cout<<"("<<re<<", "<<im<<")"<<endl; } private: double re; double im; };
  • 45. Default constructor class Complex { public: // default constructor Complex() { re = 0; im = 0; } ... }; int main() { Complex a; a.printOut(); return 0; } 45
  • 46. Parametrized constructor 46 class Complex { public: // parametrized constructor Complex(double x, double y) { re = x; im = y; } ... }; int main() { Complex a; Complex b(1.5, 2.3); a.printOut(); b.printOut(); return 0; }
  • 47. Copy constructor 47 class Complex { public: // copy constructor Complex(Complex& x) { re = x.re; im = x.im; } ... }; int main() { Complex a; Complex b(1.5, 2.3); Complex c = b; a.printOut(); b.printOut(); c.printOut(); return 0; }
  • 48. Conversion constructor (single argument) 48 class Complex { public: // conversion constructor Complex(double x) { re = x; im = 0; } ... }; int main() { Complex a = 1.5; Complex b; b = 5.6; a.printOut(); b.printOut(); return 0; }
  • 49. class Complex { public: // conversion constructor explicit Complex(double x) { re = x; im = 0; } ... }; int main() { Complex a = 1.5; // does not work Complex b(1.5); // works a = 5.6; // does not work b = Complex(5.6); // works a.printOut(); b.printOut(); return 0; } Explicit conversion constructor 49
  • 50. Initializing list 50 class Complex { public: // default constructor Complex(): re(0), im(0) {} // parametrized constructor Complex(double x, double y): re(x), im(y) {} // conversion constructor Complex(double x): re(x), im(0) {} // copy constructor Complex(Complex& c): re(c.re), im(c.im) {} ... };
  • 51. Destructor 51 class Space { public: Space(): sz(1) { ptr = new int[sz]; cout<<"Creating a Space("<<sz <<") object"<<endl; } Space(int s) : sz(s) { ptr = new int[sz]; cout<<"Creating a Space("<<sz <<") object"<<endl; } ~Space() { delete[] ptr; cout<<"Deleting a Space("<<sz <<") object"<<endl; } private: int * ptr; const int sz; }; Space s1; void fn() { Space s4(4); static Space s5(5); } int main() { Space s2(2); Space s3(3); fn(); { Space s6(6); { fn(); Space s7(7); } } }
  • 52. Constructors/Destructors calling order 52 Space s1; void fn() { Space s4(4); static Space s5(5); } int main() { Space s2(2); Space s3(3); fn(); { Space s6(6); { fn(); Space s7(7); } } } Creating a Space(1) object Creating a Space(2) object Creating a Space(3) object Creating a Space(4) object Creating a Space(5) object Deleting a Space(4) object Creating a Space(6) object Creating a Space(4) object Deleting a Space(4) object Creating a Space(7) object Deleting a Space(7) object Deleting a Space(6) object Deleting a Space(3) object Deleting a Space(2) object Deleting a Space(5) object Deleting a Space(1) object
  • 53. Setters & Getters 53 class Complex { public: // Constructors go here void setRe(double x) { re = x; } void setIm(double y) { im = y; } double getRe() { return re; } double getIm() { return im; } private: double re; double im; }; int main() { Complex a(1, 2); Complex b; b.setRe(3); b.setIm(5); cout << a.getRe() << ", " << a.getIm() << endl; cout << b.getRe() << ", " << b.getIm() << endl; }
  • 54. Constant objects and constant methods 54 class Complex { public: // Constructors go here void setRe(double x) { re = x; } void setIm(double y) { im = y; } double getRe() { return re; } double getIm() { return im; } private: double re; double im; }; int main() { const Complex a(1, 2); Complex b; b.setRe(3); b.setIm(5); cout << a.getRe() << ", " << a.getIm() << endl; // Error cout << b.getRe() << ", " << b.getIm() << endl; }
  • 55. Constant objects and constant methods 55 class Complex { public: // Constructors go here void setRe(double x) { re = x; } void setIm(double y) { im = y; } double getRe() const { return re; } double getIm() const { return im; } private: double re; double im; }; int main() { const Complex a(1, 2); Complex b; b.setRe(3); b.setIm(5); cout << a.getRe() << ", " << a.getIm() << endl; // Works fine now cout << b.getRe() << ", " << b.getIm() << endl; }
  • 56. class Date { public: Date(): day(1), month(1), year(1970) { } Date(int d, int m, int y): day(d), month(m), year(y) { } void setDay(int d) { day = d; } void setMonth(int m) { month = m; } void setYear(int y) { year = y; } int getDay() const { return day; } int getMonth() const { return month; } int getYear() const { return year; } private: int day, month, year; }; class Person { public: Person(): name("name"), birthDate(Date()) { } Person(string n, int d, int m, int y): name(n), birthDate(Date(d, m, y)) { } Person(string n, Date d): name(n), birthDate(d) { } string getName() const { return name; } Date getBirthDate() const { return birthDate; } private: string name; Date birthDate; }; Hierarchical object composition 56
  • 57. Hierarchical object composition 57 void printOut(const Date& d) { cout << d.getDay() << "/" << d.getMonth() << "/" << d.getYear(); } void printOut(const Person& p) { cout << p.getName() << ": "; printOut(p.getBirthDate()); } int main() { Person p1; Person p2("Youssof", 22, 10, 2015); Date bd(4,10,2017); Person p3(“Firas", bd); printOut(p1); cout << endl; printOut(p2); cout << endl; printOut(p3); cout << endl; return 0; } name: 1/1/1970 Youssof: 22/10/2015 Firas: 4/10/2017
  • 58. Friend functions 58 class Date { public: Date(): day(1), month(1), year(1970) { } Date(int d, int m, int y): day(d), month(m), year(y) { } void setDay(int d) { day = d; } void setMonth(int m) { month = m; } void setYear(int y) { year = y; } int getDay() const { return day; } int getMonth() const { return month; } int getYear() const { return year; } friend void printOut(const Date& d); private: int day, month, year; }; void printOut(const Date& d) { cout << d.day << "/" << d.month << "/" << d.year; }
  • 59. Friend functions 59 class Person { public: Person(): name("name"), birthDate(Date()) { } Person(string n, int d, int m, int y): name(n), birthDate(Date(d, m, y)) { } Person(string n, Date d): name(n), birthDate(d) { } string getName() const { return name; } Date getBirthDate() const { return birthDate; } friend void printOut(const Person& p); private: string name; Date birthDate; }; void printOut(const Person& p) { cout << p.name << ": "; printOut(p.birthDate); }
  • 60. Friend classes 60 class Date { public: ... friend class Display; private: ... }; class Display { public: void printOut(const Date& d) { cout << d.day << "/" << d.month << "/" << d.year; } void printOut(const Person& p) { cout << p.name << ": "; printOut(p.birthDate); } }; class Person { public: ... friend class Display; private: ... }; int main() { Person p1; Person p2("Youssof", 22, 10, 2015); Date bd(4,10,2017); Person p3("Firas", bd); Display disp; disp.printOut(p1); cout << endl; disp.printOut(p2); cout << endl; disp.printOut(p3); cout << endl; return 0; }
  • 61. Friend class methods 61 class Date; class Person; class Display { public: void printOut(const Date& d); void printOut(const Person& p); }; class Date { public: ... friend void Display::printOut(const Date& d); private: ... }; class Person { public: ... friend void Display::printOut(const Person& p); private: ... }; void Display::printOut(const Date& d) { cout << d.day << "/" << d.month << "/" << d.year; } void Display::printOut(const Person& p) { cout << p.name << ": "; printOut(p.birthDate); } int main() { Person p1; Person p2("Youssof", 22, 10, 2015); Date bd(4,10,2017); Person p3("Firas", bd); Display disp; disp.printOut(p1); cout << endl; disp.printOut(p2); cout << endl; disp.printOut(p3); cout << endl; return 0; }
  • 62. class Complex { private: double re, im; public: Complex() { re = 0; im = 0; } Complex(double x, double y) { re = x; im = y; } void printOut() { cout<<"("<<re<<", "<<im<<")"<<endl; } }; int main() { Complex a, b(1,2); Complex * p1 = new Complex; Complex * p2 = new Complex(5,8); a.printOut(); b.printOut(); (*p1).printOut(); p2->printOut(); delete p1; delete p2; return 0; } Pointers to objects (new & delete operators) 62
  • 63. class Complex { private: double re, im; public: Complex() { re = 0; im = 0; } Complex(double re, double im) { this->re = re; this->im = im; } void printOut() { cout<<"("<<re<<", "<<im<<")"<<endl; } }; int main() { Complex a, b(1,2); Complex * p1 = new Complex; Complex * p2 = new Complex(5,8); a.printOut(); b.printOut(); (*p1).printOut(); p2->printOut(); delete p1; delete p2; return 0; } Object self-referencing (this keyword) 63
  • 64. Static data members 64 class Counter { private: string name; int count; public: Counter(string n): name(n) { ++count; cout<<"Object "<<name <<" is created"<<endl; } ~Counter() { --count; cout<<"Object "<<name <<" is deleted"<<endl; } int getCount() { return count; } }; int main() { Counter a("a"); cout<<"There is/are " <<a.getCount() <<" Counter object(s) now"<<endl; Counter b("b"); cout<<"There is/are " <<b.getCount() <<" Counter object(s) now"<<endl; return 0; }
  • 65. Static data members 65 class Counter { private: string name; static int count; public: Counter(string n): name(n) { ++count; cout<<"Object "<<name <<" is created"<<endl; } ~Counter() { --count; cout<<"Object "<<name <<" is deleted"<<endl; } int getCount() { return count; } }; int Counter::count = 0; Object a is created There is/are 1 Counter object(s) now Object b is created There is/are 2 Counter object(s) now Object b is deleted Object a is deleted int main() { Counter a("a"); cout<<"There is/are " <<a.getCount() <<" Counter object(s) now"<<endl; Counter b("b"); cout<<"There is/are " <<b.getCount() <<" Counter object(s) now"<<endl; return 0; }
  • 66. Static methods 66 class Counter { private: string name; static int count; public: Counter(string n): name(n) { ++count; cout<<"Object "<<name <<" is created"<<endl; } ~Counter() { --count; cout<<"Object "<<name <<" is deleted"<<endl; } static int getCount() { return count; } }; int Counter::count = 0; Object a is created There is/are 1 Counter object(s) now Object b is created There is/are 2 Counter object(s) now Object b is deleted Object a is deleted int main() { Counter a("a"); cout<<"There is/are " <<Counter::getCount() <<" Counter object(s) now"<<endl; Counter b("b"); cout<<"There is/are " <<Counter::getCount() <<" Counter object(s) now"<<endl; return 0; }
  • 67. Revision over functions 67 int maximum(int a, int b) { if (a > b) return a; else return b; } int maximum(int a, int b, int c) { if (a > b && a > c) return a; else if (b > c) return b; else return c; } int maximum(int a, int b) { return a > b? a : b; } int maximum(int a, int b, int c) { return a>b && a>c? a : (b > c? b : c); } int maximum(int a, int b, int c) { return a>maximum(b,c)? a:maximum(b,c); } int maximum(int a, int b, int c) { return maximum(a, maximum(b,c)); }
  • 68. Default argument values of functions 68 int sum(int a, int b) { return a + b; } int sum(int a, int b, int c) { return a + b + c; } int sum(int a, int b, int c, int d) { return a + b + c + d; } int main() { int a = 3, b = 4, c = 5, d = 6; cout << sum(a, b) << endl; cout << sum(a, b, c) << endl; cout << sum(a, b, c, d) << endl; return 0; } int sum(int a, int b, int c=0, int d=0) { return a + b + c + d; } int main() { int a = 3, b = 4, c = 5, d = 6; cout << sum(a, b) << endl; cout << sum(a, b, c) << endl; cout << sum(a, b, c, d) << endl; return 0; } 7 12 18
  • 69. Default arguments inside classes 69 class Complex { private: double re, im; public: Complex(double x = 0, double y = 0) : re(x), im(y) {} ... }; class Complex { private: double re, im; public: Complex(double=0, double=0); ... }; Complex::Complex(double x, double y) : re(x), im(y) {}
  • 70. Some function overloading restrictions • Function declarations that differ only in the return type are equivalent. • Member function declarations with the same name and the name parameter-type-list cannot be overloaded if any of them is a static member function declaration. • Parameter declarations that differ only in a pointer * versus an array [] are equivalent. • Parameter declarations that differ only in the presence or absence of const and/or volatile are equivalent. • Two parameter declarations that differ only in their default arguments are equivalent. 70
  • 71. Recursion Which one is better? 71 long factorial(int n); int main() { cout << factorial(5); return 0; } long factorial(int n) { long result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; } long factorial(int n) { if (n<=1) return 1; return n * factorial(n-1); }
  • 72. Recursion 72 int fib(int n) { if (n <= 1) return n; return fib(n-1)+fib(n-2); } int main() { for (int i = 0; i < 10; i++) cout << fib(i) << endl; return 0; }
  • 73. Operators overloading 73 int main() { string s1 = "Hello"; string s2 = "world!"; string s3 = s1 + ", " + s2; cout << s1 << ", " << s2 << endl; cout << s3 << endl; return 0; }
  • 74. class Complex { private: double re, im; public: Complex(double x=0, double y=0): re(x), im(y) {} void print() const { cout << "(" << re << ", " << im << ")"; } Complex operator+(const Complex c) { return Complex(re + c.re, im + c.im); } }; int main() { Complex a(1, 4), b(5, -7); Complex c = a + b; cout << "a: "; a.print(); cout << endl; cout << "b: "; b.print(); cout << endl; cout << "c: "; c.print(); cout << endl; return 0; } Operator overloading (member function) 74 Complex Complex::operator+(const Complex c) { return Complex(re + c.re, im + c.im); }
  • 75. Operator overloading (non-member function) With friend functions: With non-friend functions: 75 class Complex { private: ... friend Complex operator+(const Complex c1, const Complex c2); }; Complex operator+(const Complex c1, const Complex c2) { return Complex(c1.re + c2.re, c1.im + c2.im); } class Complex { private: ... // setters & getters }; Complex operator+ (const Complex c1, const Complex c2) { return Complex(c1.getRe() + c2.getRe(), c1.getIm() + c2.getIm()); }
  • 76. Conversion function overloading • Converts the object into another type • Member method overloading only 76 class Ratio { private: double x, y; public: Ratio(double a = 0, double b = 0) : x(a), y(b) {} Ratio(const Ratio& c) : x(c.x), y(c.y) {} void printOut() { cout << x << "/" << y; } }; class Complex { private: double re, im; public: Complex(double x = 0, double y = 0) : re(x), im(y) {} Complex(const Complex& c) : re(c.re), im(c.im) {} void printOut() { cout<<"("<<re<<", "<<im<<")"; } operator double() { return sqrt(re * re + im * im); } operator Ratio() { return Ratio(re, im); } operator string() { stringstream ss; ss<<"("<<re<<", "<<im<<")"; return ss.str(); } }; int main() { Complex c(3.4, 5.6); c.printOut(); cout << endl; double d = c; cout << d << endl; Ratio r = c; r.printOut(); cout << endl; return 0; }
  • 77. Pre-/Post-increment/decrement operators 77 class Store { private: int value; public: Store(int v = 0) : value(v) {} Store(Store& s) : value(s.value) {} operator int() { return value; } // pre-increment operator Store& operator++() { value++; return *this; } // post-increment operator Store operator++(int) { Store copy(*this); ++(*this); return copy; } }; int main() { Store a(5); cout << a << endl; cout << ++a << endl; cout << a << endl; cout << a++ << endl; cout << a << endl; } operator++();
  • 78. Operator overloading restrictions • Almost any operator can be overloaded in C++. Except: • member selector – (.) • scope operator – (::) • ternary operator – (? :) • sizeof • Only built-in operators can be overloaded. New operators can not be created. • Arity (number of operands) of the operators cannot be changed. • Precedence and associativity of the operators cannot be changed. • Overloaded operators cannot have default arguments except the function call operator () which can have default arguments. • Operators cannot be overloaded for built in types only. At least one operand must be used defined type. • Assignment (=), subscript ([]), function call (“()”), and member selection (->) operators must be defined as member functions • Except the operators specified in the last point, all other operators can be either member functions or a non member functions. • Some operators like (assignment)=, (address)& and comma (,) are by default overloaded. 78
  • 79. C++ operator precedence 79 Precedence Operator Description Associativity 1 :: Scope resolution Left-to-right 2 a++ a-- Suffix/postfix increment and decrement type() type{} Functional cast a() Function call a[] Subscript . -> Member access 3 ++a --a Prefix increment and decrement Right-to-left +a -a Unary plus and minus ! ~ Logical NOT and bitwise NOT (type) C-style cast *a Indirection (dereference) &a Address-of sizeof Size-of[note 1] co_await await-expression (C++20) new new[] Dynamic memory allocation delete delete[] Dynamic memory deallocation 4 .* ->* Pointer-to-member Left-to-right 5 a*b a/b a%b Multiplication, division, and remainder 6 a+b a-b Addition and subtraction
  • 80. C++ operator precedence 80 Precedence Operator Description Associativity 7 << >> Bitwise left shift and right shift Left-to-right 8 <=> Three-way comparison operator (since C++20) 9 < <= For relational operators < and ≤ respectively > >= For relational operators > and ≥ respectively 10 == != For relational operators = and ≠ respectively 11 & Bitwise AND 12 ^ Bitwise XOR (exclusive or) 13 | Bitwise OR (inclusive or) 14 && Logical AND 15 || Logical OR 16 a?b:c Ternary conditional[note 2] Right-to-left throw throw operator co_yield yield-expression (C++20) = Direct assignment (provided by default for C++ classes) += -= Compound assignment by sum and difference *= /= %= Compound assignment by product, quotient, and remainder <<= >>= Compound assignment by bitwise left shift and right shift &= ^= |= Compound assignment by bitwise AND, XOR, and OR 17 , Comma Left-to-right
  • 81. OOP concepts: Inheritance 81 class SuperClass { public: int superValue; }; class SubClass : public SuperClass { public: int subValue; }; int main() { SubClass sub; sub.subValue = 2; sub.superValue = 5; cout << sub.subValue << endl; cout << sub.superValue << endl; return 0; }
  • 82. Modes of Inheritance 82 class A { public: int x; protected: int y; private: int z; }; class B : public A { // x is public // y is protected // z is not accessible from B }; class C : protected A { // x is protected // y is protected // z is not accessible from C }; // 'private' is default for classes class D : private A { // x is private // y is private // z is not accessible from D };
  • 83. Constructor/Destructor calling order 83 class A { public: A() { cout << "A object createdn"; } ~A() { cout << "A object deletedn"; } }; class B : public A { public: B() { cout << "B object createdn"; } ~B() { cout << "B object deletedn"; } }; class C : public B { public: C() { cout << "C object createdn"; } ~C() { cout << "C object deletedn"; } }; int main() { A x; B y; C z; return 0; } A object created A object created B object created A object created B object created C object created C object deleted B object deleted A object deleted B object deleted A object deleted A object deleted
  • 84. Multiple inheritance 84 class Base { ... }; class X : public Base { ... }; class Y : public Base { ... }; class XY : public X, public Y { ... };
  • 85. Multiple inheritance (example) 85 class Vehicle { public: Vehicle() { cout << "This is a Vehiclen"; } }; class FourWheeler { public: FourWheeler() { cout << "This is a 4-wheeler Vehiclen"; } }; class Car : public Vehicle, public FourWheeler { }; int main() { Car car; return 0; }
  • 86. class A { public: A() { cout << "A() constructor is calledn"; } A(int n) { cout << "A(int) constructor is calledn"; } ~A() { cout << "~A() destructor is calledn"; } }; class B : public A { public: B() { cout << "B() constructor is calledn"; } B(int n) { cout << "B(int) constructor is calledn"; } ~B() { cout << "~B() destructor is calledn"; } }; class C : public A { public: C() { cout << "C() constructor is calledn"; } C(int n) { cout << "C(int) constructor is calledn"; } ~C() { cout << "~C() destructor is calledn"; } }; class D : public B, public C { public: D() { cout << "D() constructor is calledn"; } D(int n) { cout << "D(int) constructor is calledn"; } ~D() { cout << "~D() destructor is calledn"; } }; int main() { D x; D y(10); return 0; } Constructor/Destructor calling order (multiple-inheritance) 86 A() constructor is called B() constructor is called A() constructor is called C() constructor is called D() constructor is called A() constructor is called B() constructor is called A() constructor is called C() constructor is called D(int) constructor is called ~D() destructor is called ~C() destructor is called ~A() destructor is called ~B() destructor is called ~A() destructor is called ~D() destructor is called ~C() destructor is called ~A() destructor is called ~B() destructor is called ~A() destructor is called
  • 87. class A { public: A() { cout << "A() constructor is calledn"; } A(int n) { cout << "A(int) constructor is calledn"; } ~A() { cout << "~A() destructor is calledn"; } }; class B : public A { public: B() { cout << "B() constructor is calledn"; } B(int n) : A(n) { cout << "B(int) constructor is calledn"; } ~B() { cout << "~B() destructor is calledn"; } }; class C : public A { public: C() { cout << "C() constructor is calledn"; } C(int n) : A(n) { cout << "C(int) constructor is calledn"; } ~C() { cout << "~C() destructor is calledn"; } }; class D : public B, public C { public: D() { cout << "D() constructor is calledn"; } D(int n) : B(n), C(n) { cout << "D(int) constructor is calledn"; } ~D() { cout << "~D() destructor is calledn"; } }; int main() { D x; D y(10); return 0; } Constructor/Destructor calling order (calling non-default constructor) 87 A() constructor is called B() constructor is called A() constructor is called C() constructor is called D() constructor is called A(int) constructor is called B(int) constructor is called A(int) constructor is called C(int) constructor is called D(int) constructor is called ~D() destructor is called ~C() destructor is called ~A() destructor is called ~B() destructor is called ~A() destructor is called ~D() destructor is called ~C() destructor is called ~A() destructor is called ~B() destructor is called ~A() destructor is called
  • 89. Multiple inheritance The diamond problem 89 class TA : public Faculty, public Student { public: TA(int x) : Student(x), Faculty(x) { cout << "TA::TA(int) calledn"; } }; int main() { TA ta1(30); } #include <iostream> using namespace std; class Person { public: Person(int x) { cout << "Person::Person(int) calledn"; } Person() { cout << "Person::Person() calledn"; } }; class Faculty : public Person { public: Faculty(int x) : Person(x) { cout << "Faculty::Faculty(int) calledn"; } }; class Student : public Person { public: Student(int x) : Person(x) { cout << "Student::Student(int) calledn"; } }; Person::Person(int) called Faculty::Faculty(int) called Person::Person(int) called Student::Student(int) called TA::TA(int) called
  • 90. Virtual multiple inheritance 90 class Base { ... }; class X : public Base { ... }; class Y : public Base { ... }; class XY : public X, public Y { ... }; class Base { ... }; class X : public virtual Base { ... }; class Y : public virtual Base { ... }; class XY : public X, public Y { ... };
  • 91. Multiple inheritance The diamond problem 91 class TA : public Faculty, public Student { public: TA(int x) : Student(x), Faculty(x) { cout << "TA::TA(int) calledn"; } }; int main() { TA ta1(30); } #include <iostream> using namespace std; class Person { public: Person(int x) { cout << "Person::Person(int) calledn"; } Person() { cout << "Person::Person() calledn"; } }; class Faculty : virtual public Person { public: Faculty(int x) : Person(x) { cout << "Faculty::Faculty(int) calledn"; } }; class Student : virtual public Person { public: Student(int x) : Person(x) { cout << "Student::Student(int) calledn"; } }; Person::Person() called Faculty::Faculty(int) called Student::Student(int) called TA::TA(int) called
  • 92. Multiple inheritance The diamond problem 92 class TA : public Faculty, public Student { public: TA(int x) : Student(x), Faculty(x), Person(x) { cout << "TA::TA(int) calledn"; } }; int main() { TA ta1(30); } #include <iostream> using namespace std; class Person { public: Person(int x) { cout << "Person::Person(int) calledn"; } Person() { cout << "Person::Person() calledn"; } }; class Faculty : virtual public Person { public: Faculty(int x) : Person(x) { cout << "Faculty::Faculty(int) calledn"; } }; class Student : virtual public Person { public: Student(int x) : Person(x) { cout << "Student::Student(int) calledn"; } }; Person::Person(int) called Faculty::Faculty(int) called Student::Student(int) called TA::TA(int) called
  • 93. class A { public: A() { cout << "A() constructor is calledn"; } A(int n) { cout << "A(int) constructor is calledn"; } ~A() { cout << "~A() destructor is calledn"; } }; class B : virtual public A { public: B() { cout << "B() constructor is calledn"; } B(int n) { cout << "B(int) constructor is calledn"; } ~B() { cout << "~B() destructor is calledn"; } }; class C : virtual public A { public: C() { cout << "C() constructor is calledn"; } C(int n) { cout << "C(int) constructor is calledn"; } ~C() { cout << "~C() destructor is calledn"; } }; class D : public B, public C { public: D() { cout << "D() constructor is calledn"; } D(int n) { cout << "D(int) constructor is calledn"; } ~D() { cout << "~D() destructor is calledn"; } }; int main() { D x; D y(10); return 0; } Constructor/Destructor calling order (virtual inheritance) 93 A() constructor is called B() constructor is called C() constructor is called D() constructor is called A() constructor is called B() constructor is called C() constructor is called D(int) constructor is called ~D() destructor is called ~C() destructor is called ~B() destructor is called ~A() destructor is called ~D() destructor is called ~C() destructor is called ~B() destructor is called ~A() destructor is called
  • 94. class A { public: A() { cout << "A() constructor is calledn"; } A(int n) { cout << "A(int) constructor is calledn"; } ~A() { cout << "~A() destructor is calledn"; } }; class B : public virtual A { public: B() { cout << "B() constructor is calledn"; } B(int n) : A(n) { cout << "B(int) constructor is calledn"; } ~B() { cout << "~B() destructor is calledn"; } }; class C : public virtual A { public: C() { cout << "C() constructor is calledn"; } C(int n) : A(n) { cout << "C(int) constructor is calledn"; } ~C() { cout << "~C() destructor is calledn"; } }; class D : public B, public C { public: D() { cout << "D() constructor is calledn"; } D(int n) : B(n), C(n) { cout << "D(int) constructor is calledn"; } ~D() { cout << "~D() destructor is calledn"; } }; int main() { D x; D y(10); return 0; } Constructor/Destructor calling order (virtual inheritance) 94 A() constructor is called B() constructor is called C() constructor is called D() constructor is called A() constructor is called B(int) constructor is called C(int) constructor is called D(int) constructor is called ~D() destructor is called ~C() destructor is called ~B() destructor is called ~A() destructor is called ~D() destructor is called ~C() destructor is called ~B() destructor is called ~A() destructor is called
  • 95. class A { public: A() { cout << "A() constructor is calledn"; } A(int n) { cout << "A(int) constructor is calledn"; } ~A() { cout << "~A() destructor is calledn"; } }; class B : public virtual A { public: B() { cout << "B() constructor is calledn"; } B(int n) : A(n) { cout << "B(int) constructor is calledn"; } ~B() { cout << "~B() destructor is calledn"; } }; class C : public virtual A { public: C() { cout << "C() constructor is calledn"; } C(int n) : A(n) { cout << "C(int) constructor is calledn"; } ~C() { cout << "~C() destructor is calledn"; } }; class D : public B, public C { public: D() { cout << "D() constructor is calledn"; } D(int n) : A(n), B(n), C(n) { cout << "D(int) constructor is calledn"; } ~D() { cout << "~D() destructor is calledn"; } }; int main() { D x; D y(10); return 0; } Constructor/Destructor calling order (virtual inheritance) 95 A() constructor is called B() constructor is called C() constructor is called D() constructor is called A(int) constructor is called B(int) constructor is called C(int) constructor is called D(int) constructor is called ~D() destructor is called ~C() destructor is called ~B() destructor is called ~A() destructor is called ~D() destructor is called ~C() destructor is called ~B() destructor is called ~A() destructor is called
  • 96. Multiple inheritance The ambiguity problem 96 class A { public: void doSomething() {...}; }; class B { public: void doSomething() {...}; }; class C : public A, public B { public: void start() { // ambiguous call doSomething(); } };
  • 97. Multiple inheritance The ambiguity problem (solution) 97 class A { public: void doSomething() {...}; }; class B { public: void doSomething() {...}; }; class C : public A, public B { public: void start() { // correct call A::doSomething(); } };
  • 98. Multiple inheritance The ambiguity problem 98 class A { public: void doSomething() {...}; }; class B { public: void doSomething() {...}; }; class C : public A, public B { public: void start() { // correct call A::doSomething(); } }; int main() { C obj; // ambiguous call obj.doSomething(); return 0; }
  • 99. Multiple inheritance The ambiguity problem (solution) 99 class A { public: void doSomething() {...}; }; class B { public: void doSomething() {...}; }; class C : public A, public B { public: void start() { // correct call A::doSomething(); } }; int main() { C obj; // correct call obj.A::doSomething(); return 0; }
  • 100. Multiple inheritance The ambiguity problem 100 #include <iostream> using namespace std; class A { public: int x; }; class B : public A { }; class C : public A { }; class D : public B, public C { }; int main() { D obj; obj.x = 5; cout << obj.x << "n"; return 0; }
  • 101. Multiple inheritance The ambiguity problem (solution) 101 #include <iostream> using namespace std; class A { public: int x; }; class B : public A { }; class C : public A { }; class D : public B, public C { }; int main() { D obj; obj.B::x = 5; obj.C::x = 7; cout << obj.B::x << "n"; cout << obj.C::x << "n"; return 0; }
  • 102. Multiple inheritance The ambiguity problem (solution) 102 #include <iostream> using namespace std; class A { public: int x; }; class B : public virtual A { }; class C : public virtual A { }; class D : public B, public C { }; int main() { D obj; obj.B::x = 5; obj.C::x = 7; cout << obj.B::x << "n"; cout << obj.C::x << "n"; return 0; }
  • 103. class Shape { protected: string name; public: Shape(string n) : name(n) { cout << "Shape " << name << " created" << endl; } string getName() const { return name; } }; class Rect : public Shape { public: Rect(string n) : Shape(n) { cout << "Rect " << name << " created" << endl; } }; int main() { Shape sh("First"); Rect r("Second"); cout << "Shape: " << sh.getName() << endl; cout << "Rect: " << r.getName() << endl; return 0; } Method overriding 103
  • 104. class Shape { protected: string name; public: Shape(string n) : name(n) { cout << "Shape " << name << " created" << endl; } void printOut() const { cout << "Shape: "<< name << endl; } }; class Rect : public Shape { public: Rect(string n) : Shape(n) { cout << "Rect " << name << " created" << endl; } void printOut() const { cout << “Rect: "<< name << endl; } }; int main() { Shape sh("First"); Rect r("Second"); sh.printOut(); r.printOut(); return 0; } Method overriding 104
  • 105. Polymorphism 105 class Shape { protected: ... }; class Rect : public Shape { ... }; class Triangle : public Shape { public: Triangle(string n) : Shape(n) { cout << "Triangle " << name << " created" << endl; } void printOut() const { cout << "Triangle: " << name << endl; } }; class Circle : public Shape { public: Circle(string n) : Shape(n) { cout << "Circle " << name << " created" << endl; } void printOut() const { cout << "Circle: " << name << endl; } };
  • 106. Polymorphism (early binding) 106 int main() { Shape s("s"); Rect r("r"); Triangle t("t"); Circle c("c"); Shape *sh; sh = &s; sh->printOut(); sh = &r; sh->printOut(); sh = &t; sh->printOut(); sh = &c; sh->printOut(); return 0; } Shape s created Shape r created Rect r created Shape t created Triangle t created Shape c created Circle c created Shape: s Shape: r Shape: t Shape: c
  • 107. Polymorphism (late binding) 107 int main() { Shape s("s"); Rect r("r"); Triangle t("t"); Circle c("c"); Shape *sh; sh = &s; sh->printOut(); sh = &r; sh->printOut(); sh = &t; sh->printOut(); sh = &c; sh->printOut(); return 0; } Shape s created Shape r created Rect r created Shape t created Triangle t created Shape c created Circle c created Shape: s Rect: r Triangle: t Circle: c class Shape { ... virtual void printOut() const { cout << "Shape: " << name << endl; } };
  • 108. Polymorphism (using references) 108 int main() { Shape s("s"); Rect r("r"); Triangle t("t"); Circle c("c"); Shape &shS = s; shS.printOut(); Shape &shR = r; shR.printOut(); Shape &shT = t; shT.printOut(); Shape &shC = c; shC.printOut(); return 0; }
  • 109. Rules for Virtual Functions • Virtual functions cannot be static and cannot be a friend function of another class. • Virtual functions should be accessed using pointer or reference of base class type to achieve run time polymorphism. • The prototype of virtual functions should be same in base as well as derived class. • They are always defined in base class and overridden in derived class. It is not mandatory for derived class to override (or re-define the virtual function), in that case base class version of function is used. • A class may have virtual destructor, but it cannot have a virtual constructor. 109
  • 110. Abstract methods (pure virtual) 110 class Shape { ... virtual void draw() = 0; }; class Rect : public Shape { ... virtual void draw() { cout << "Drawing Rect " << name << endl; }; }; class Triangle : public Shape { ... virtual void draw() { cout << "Drawing Triangle " << name << endl; }; }; class Circle : public Shape { ... virtual void draw() { cout << "Drawing Circle " << name << endl; }; }; int main() { Rect r("r"); Triangle t("t"); Circle c("c"); Shape *sh; sh = &r; sh->draw(); sh = &t; sh->draw(); sh = &c; sh->draw(); return 0; }
  • 111. Abstract vs. Concrete classes • Any class containing abstract method is abstract • Inherited abstract method should be implemented in the subclass or else the subclass becomes abstract • Abstract classes cannot be instantiated (cannot create objects of it). • Pointers to abstract class objects are possible. However, they should point to concrete object of the class (instances of the subclasses). 111
  • 112. Virtual destructor 112 class Shape { protected: string name; public: Shape(string n="unknown") : name(n) { cout << "Shape " << name << " created" << endl; } ~Shape() { cout << "Shape " << name << " destroyed" << endl; } virtual void printOut() const { cout << "Shape: " << name << endl; } virtual void draw() = 0; }; class Rect : public Shape { public: Rect(string n) : Shape(n) { cout << "Rect " << name << " created" << endl; } ~Rect() { cout << "Rect " << name << " destroyed" << endl; } void printOut() const { cout << "Rect: " << name << endl; } virtual void draw() { cout << "Drawing Rect " << name << endl; }; };
  • 113. Virtual destructor 113 void printShape(Shape *s) { s->printOut(); } void drawShape(Shape *s) { s->draw(); } int main() { Rect r("r"); Triangle t("t"); printShape(&r); drawShape(&r); printShape(&t); drawShape(&t); return 0; } Shape r created Rect r created Shape t created Triangle t created Rect: r Drawing Rect r Triangle: t Drawing Triangle t Triangle t destroyed Shape t destroyed Rect r destroyed Shape r destroyed
  • 114. Virtual destructor 114 int main() { Shape *sh; sh = new Rect("r"); printShape(sh); drawShape(sh); delete sh; sh = new Triangle("t"); printShape(sh); drawShape(sh); delete sh; return 0; } Shape r created Rect r created Rect: r Drawing Rect r Shape r destroyed Shape t created Triangle t created Triangle: t Drawing Triangle t Shape t destroyed
  • 115. class Shape { ... virtual ~Shape() { cout << "Shape " << name << " destroyed" << endl; } ... }; int main() { Shape *sh; sh = new Rect("r"); printShape(sh); drawShape(sh); delete sh; sh = new Triangle("t"); printShape(sh); drawShape(sh); delete sh; return 0; } Virtual destructor 115 Shape r created Rect r created Rect: r Drawing Rect r Rect r destroyed Shape r destroyed Shape t created Triangle t created Triangle: t Drawing Triangle t Triangle t destroyed Shape t destroyed
  • 116. Anonymous object 116 int main() { Rect r("r"); Triangle *t = new Triangle("t"); Triangle *p = t; delete t; return 0; } Shape r created Rect r created Shape t created Triangle t created Triangle t destroyed Shape t destroyed Rect r destroyed Shape r destroyed
  • 117. class Button { protected: string label; public: Button(string l="unlabel") : label(l) { cout << "Button " << label << " created" << endl; } virtual ~Button() { cout << "Button " << label << " destroyed" << endl; } virtual void onClick() = 0; }; int main() { class : public Button { public: virtual void onClick() { cout << "Save button clicked" << endl; } void setLabel(string l) { label = l; } } saveBtn; saveBtn.setLabel("Save"); saveBtn.onClick(); return 0; } Anonymous class 117
  • 118. Templates 118 int maximum(int a, int b) { return a > b? a : b; } int maximum(double a, double b) { return a > b? a : b; } int sum(int a, int b, int c, int d) { return a + b + c + d; } double sum(double a, double b, double c, double d) { return a + b + c + d; }
  • 119. Function template 119 template <class T> T maximum(T a, T b) { return a > b? a : b; } template <typename T> T sum(T a, T b, T c, T d) { return a + b + c + d; } int main() { cout << maximum(1, 4) << endl; cout << maximum(1.2, 4.5) << endl; // cout << maximum(5.3, 2) << endl; does not work cout << maximum<double>(5.3, 2) << endl; // This works cout << sum(1, 2, 3, 4) << endl; cout << sum(1.2, 2.3, 3.4, 4.5) << endl; return 0; }
  • 120. Function template specialization 120 template <class T> void fun(T a) { cout << "Main fun() template: " << a << endl; } template<> void fun(double a) { cout << "double fun() template: " << a << endl; } int main() { fun(1); fun(3.14); fun("Hello"); return 0; } Main fun() template: 1 Main fun() template: 3.14 Main fun() template: Hello Main fun() template: 1 double fun() template: 3.14 Main fun() template: Hello
  • 121. Class templates 121 template <class T> class Stack { private: T elems[10]; // elements public: void push(T const &); // push element T pop(); // pop element bool empty() const { // return true if empty. ... } }; template <class T> void Stack<T>::push(T const &elem) { // append copy of passed element } template <class T> T Stack<T>::pop() { // remove last element } int main() { Stack<int> intStack; // stack of ints Stack<string> stringStack; // stack of strings // manipulate int stack intStack.push(7); cout << intStack.pop() << endl; // manipulate string stack stringStack.push("hello"); cout << stringStack.pop() << endl; return 0; }
  • 122. Class templates specialization 122 template <class T> class Stack { private: T elems[10]; // elements public: void push(T const &); // push element T pop(); // pop element bool empty() const { // return true if empty. ... } }; template <> class Stack<string> { ... };
  • 123. Class templates with default type 123 template <class T = double> class Stack { private: T elems[10]; // elements public: void push(T const &); // push element T pop(); // pop element bool empty() const { // return true if empty. ... } }; int main() { Stack<int> intStack; // stack of ints Stack<> doubleStack; // stack of doubles // manipulate int stack intStack.push(7); cout << intStack.pop() << endl; // manipulate double stack doubleStack.push(3.14); cout << doubleStack.pop() << endl; return 0; }
  • 124. Class templates with nontype parameters 124 template <class T, int sSize> class Stack { private: T elems[sSize]; // elements public: void push(T const &); // push element T pop(); // pop element bool empty() const { // return true if empty. ... } }; template <class T, int sSize> void Stack<T,sSize>::push(T const &elem) { // append copy of passed element } template <class T, int sSize> T Stack<T,sSize>::pop() { // remove last element } int main() { Stack<int, 10> intStack; Stack<string, 20> stringStack; // manipulate int stack intStack.push(7); cout << intStack.pop() << endl; // manipulate string stack stringStack.push("hello"); cout << stringStack.pop() << endl; return 0; }
  • 125. Class templates with default type 125 template <class T = double> class Stack { ... }; int main() { // stack of ints Stack<int> intStack; // stack of doubles Stack<> doubleStack; ... return 0; } template <class T=double, int sSize=30> class Stack { ... }; int main() { // stack of 10 ints Stack<int, 10> intStack; // stack of 30 strings Stack<string> stringStack; // stack of 30 doubles Stack<> doubleStack; ... return 0; }
  • 126. class Date { private: int day, month, year; public: Date(int d=11, int m=11, int y=1975); void printOut(); friend ostream& operator<<(ostream& os, const Date& dt); friend istream& operator>> (istream& is, Date& dt); }; Date::Date(int d, int m, int y) : day(d<1?1:d>31?31:d) , month(m<1?1:m>12?12:m) , year(y<0?-y:y) {} void Date::printOut() { cout << day << "/" << month << "/" << year; } ostream& operator<<(ostream& os, const Date& dt) { os << dt.day << "/" << dt.month << "/" << dt.year; return os; } istream& operator>> (istream& is, Date& dt) { is >> dt.day >> dt.month >> dt.year; return is; } Overloading output/input streams 126 int main() { Date d1, d2(11, 12, 2019); d1.printOut(); cout << endl; d2.printOut(); cout << endl; cin >> d2; cout << d1 << endl; cout << d2 << endl; return 0; }
  • 127. Sorting Algorithms • Bubble sort • Selection sort • Insertion sort • Quick sort • Merge Sort • Heap Sort • Radix Sort • Counting Sort • Bucket Sort • ShellSort 127 void swap(int &x, int &y) { int temp = x; x = y; y = temp; } void printArray(int arr[], int size) { for (int i = 0; i < size; i++) cout << arr[i] << " "; cout << endl; } ... int main() { int arr[] = {64, 34, 25, 12, 22, 11, 90}; int n = sizeof(arr) / sizeof(arr[0]); printArray(arr, n); methodOfSort(arr, n); cout << "Sorted array: n"; printArray(arr, n); return 0; }
  • 128. void bubbleSort(int arr[], int n) { for (int i = 0; i < n - 1; i++) for (int j = 0; j < n - i - 1; j++) if (arr[j] > arr[j + 1]) swap(arr[j], arr[j + 1]); } int main() { int arr[] = {64, 34, 25, 12, 22, 11, 90}; printArray(arr, n); int n = sizeof(arr) / sizeof(arr[0]); bubbleSort(arr, n); cout << "Sorted array: n"; printArray(arr, n); return 0; } Bubble Sort 128
  • 129. Selection Sort 129 void selectionSort(int arr[], int n) { int min_idx; for (int i = 0; i < n - 1; i++) { min_idx = i; for (int j = i + 1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; swap(arr[min_idx], arr[i]); } } int main() { int arr[] = {64, 34, 25, 12, 22, 11, 90}; printArray(arr, n); int n = sizeof(arr) / sizeof(arr[0]); selectionSort(arr, n); cout << "Sorted array: n"; printArray(arr, n); return 0; }
  • 130. Insertion Sort 130 void insertionSort(int arr[], int n) { int i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i - 1; while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; } } int main() { int arr[] = {64, 34, 25, 12, 22, 11, 90}; printArray(arr, n); int n = sizeof(arr) / sizeof(arr[0]); insertionSort(arr, n); cout << "Sorted array: n"; printArray(arr, n); return 0; }
  • 131. Quick Sort 131 int partition(int arr[], int low, int high) { int pivot = arr[high]; int i = (low - 1); for (int j = low; j <= high - 1; j++) { if (arr[j] <= pivot) { i++; swap(arr[i], arr[j]); } } swap(arr[i + 1], arr[high]); return (i + 1); } void quickSort(int arr[], int low, int high) { if (low < high) { int pi = partition(arr, low, high); quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); } } int main() { int arr[] = {64, 34, 25, 12, 22, 11, 90}; printArray(arr, n); int n = sizeof(arr) / sizeof(arr[0]); quickSort(arr, 0, n-1); cout << "Sorted array: n"; printArray(arr, n); return 0; }
  • 132. Standard Template Library (STL) • A set of C++ template classes to provide common programming data structures and functions such as lists, stacks, arrays, etc. • STL has four components: • Containers • Algorithms • Functions (Functors) • Iterators 132
  • 133. STL Containers • A container is a holder object that stores a collection of other objects (its elements). • The container manages the storage space for its elements and provides member functions to access them, either directly or through iterators. • Containers replicate structures very commonly used in programming: dynamic arrays (vector), queues (queue), stacks (stack), heaps (priority_queue), linked lists (list), trees (set), associative arrays (map)… • Many containers have several member functions in common, and share functionalities. The decision of which type of container to use for a specific need does not generally depend only on the functionality offered by the container, but also on the efficiency of some of its members (complexity). • stack, queue and priority_queue are implemented as container adaptors. Container adaptors are not full container classes, but classes that provide a specific interface relying on an object of one of the container classes (such as deque or list) to handle the elements. The underlying container is encapsulated in such a way that its elements are accessed by the members of the container adaptor independently of the underlying container class used. 133
  • 134. STL Container class templates • Sequence containers: • array (C++11): Array class (class template) • vector: Vector (class template) • deque: Double ended queue (class template) • forward_list (C++11): Forward list (class template) • list: List (class template) • Container adaptors: • stack: LIFO stack (class template) • queue: FIFO queue (class template) • priority_queue: Priority queue (class template) 134
  • 135. STL Container class templates • Associative containers: • set: Set (class template) • multiset: Multiple-key set (class template) • map: Map (class template) • multimap: Multiple-key map (class template) • Unordered associative containers: • unordered_set (C++11): Unordered Set (class template) • unordered_multiset (C++11): Unordered Multiset (class template) • unordered_map (C++11): Unordered Map (class template) • unordered_multimap (C++11): Unordered Multimap (class template) 135
  • 136. STL Algorithms <algorithm> • Non-modifying sequence operations: • all_of : Test condition on all elements in range (function template) • any_of : Test if any element in range fulfills condition (function template) • none_of : Test if no elements fulfill condition (function template) • for_each: Apply function to range (function template) • find: Find value in range (function template) • find_if: Find element in range (function template) • find_if_not: Find element in range (negative condition) (function template) • find_end: Find last subsequence in range (function template) • find_first_of: Find element from set in range (function template) • adjacent_find: Find equal adjacent elements in range (function template) 136
  • 137. STL Algorithms <algorithm> • Non-modifying sequence operations: • count: Count appearances of value in range (function template) • count_if: Return number of elements in range satisfying condition (function template) • mismatch: Return first position where two ranges differ (function template) • equal: Test whether the elements in two ranges are equal (function template) • is_permutation: Test whether range is permutation of another (function template) • search: Search range for subsequence (function template) • search_n: Search range for elements (function template) 137
  • 138. STL Algorithms <algorithm> • Modifying sequence operations: • copy: Copy range of elements (function template) • copy_n: Copy elements (function template) • copy_if: Copy certain elements of range (function template) • copy_backward: Copy range of elements backward (function template) • move: Move range of elements (function template) • move_backward: Move range of elements backward (function template) • swap: Exchange values of two objects (function template) • swap_ranges: Exchange values of two ranges (function template) • iter_swap: Exchange values of objects pointed to by two iterators (function template) • transform: Transform range (function template) 138
  • 139. STL Algorithms <algorithm> • Modifying sequence operations: • replace: Replace value in range (function template) • replace_if: Replace values in range (function template) • replace_copy: Copy range replacing value (function template) • replace_copy_if: Copy range replacing value (function template) • fill: Fill range with value (function template) • fill_n: Fill sequence with value (function template) • generate: Generate values for range with function (function template) • generate_n: Generate values for sequence with function (function template) • remove: Remove value from range (function template) • remove_if: Remove elements from range (function template) • remove_copy: Copy range removing value (function template) • remove_copy_if: Copy range removing values (function template) 139
  • 140. STL Algorithms <algorithm> • Modifying sequence operations: • unique: Remove consecutive duplicates in range (function template) • unique_copy: Copy range removing duplicates (function template) • reverse: Reverse range (function template) • reverse_copy: Copy range reversed (function template) • rotate: Rotate left the elements in range (function template) • rotate_copy: Copy range rotated left (function template) • random_shuffle: Randomly rearrange elements in range (function template) • shuffle: Randomly rearrange elements in range using generator (function template) 140
  • 141. STL Algorithms <algorithm> • Partitions: • is_partitioned: Test whether range is partitioned (function template) • partition: Partition range in two (function template) • stable_partition: Partition range in two - stable ordering (function template) • partition_copy: Partition range into two (function template) • partition_point: Get partition point (function template) 141
  • 142. STL Algorithms <algorithm> • Sorting: • sort: Sort elements in range (function template) • stable_sort: Sort elements preserving order of equivalents (function template) • partial_sort: Partially sort elements in range (function template) • partial_sort_copy: Copy and partially sort range (function template) • is_sorted: Check whether range is sorted (function template) • is_sorted_until: Find first unsorted element in range (function template) • nth_element: Sort element in range (function template) 142
  • 143. STL Algorithms <algorithm> • Sorting: • sort: Sort elements in range (function template) • stable_sort: Sort elements preserving order of equivalents (function template) • partial_sort: Partially sort elements in range (function template) • partial_sort_copy: Copy and partially sort range (function template) • is_sorted: Check whether range is sorted (function template) • is_sorted_until: Find first unsorted element in range (function template) • nth_element: Sort element in range (function template) 143
  • 144. STL Algorithms <algorithm> • Binary search (operating on partitioned/sorted ranges): • lower_bound: Return iterator to lower bound (function template) • upper_bound: Return iterator to upper bound (function template) • equal_range: Get subrange of equal elements (function template) • binary_search: Test if value exists in sorted sequence (function template) 144
  • 145. STL Algorithms <algorithm> • Merge (operating on sorted ranges): • merge: Merge sorted ranges (function template) • inplace_merge: Merge consecutive sorted ranges (function template) • includes: Test whether sorted range includes another sorted range (function template) • set_union: Union of two sorted ranges (function template) • set_intersection: Intersection of two sorted ranges (function template) • set_difference: Difference of two sorted ranges (function template) • set_symmetric_difference: Symmetric difference of two sorted ranges (function template) 145
  • 146. STL Algorithms <algorithm> • Heap: • push_heap: Push element into heap range (function template) • pop_heap: Pop element from heap range (function template) • make_heap: Make heap from range (function template) • sort_heap: Sort elements of heap (function template) • is_heap: Test if range is heap (function template) • is_heap_until: Find first element not in heap order (function template) 146
  • 147. STL Algorithms <algorithm> • Min/max: • min: Return the smallest (function template) • max: Return the largest (function template) • minmax: Return smallest and largest elements (function template) • min_element: Return smallest element in range (function template) • max_element: Return largest element in range (function template) • minmax_element: Return smallest and largest elements in range (function template) • Other: • lexicographical_compare: Lexicographical less-than comparison (function template) • next_permutation: Transform range to next permutation (function template) • prev_permutation: Transform range to previous permutation (function template) 147