You are on page 1of 208

CS201, IITG

Learn C++ in 9 Hours


Sanasam Ranbir Singh
Note to students:
1. Lab classes from Monday(09-0-!010"
!. #reate Lab users account (non-#S$ student"
%. #hec& course site for 'R(#)*#$ 'R+,R(MS
htt-:../atinga.iitg.ernet.in.0saradhi.cs!01.html
Before OOP
1ata )y-e 2 1ata Structure 2 (bstract 1ata
)y-e 2 +b/ect +riented 'rogramming
A point in space
Many points in space
*f 3e consider the abo4e -oints as the data to be -rocessed by a
-rogram5 ho3 do 3e arrange them in memory6
Before OOP
1ata )y-e 2 1ata Structure 2 (bstract 1ata
)y-e 2 +b/ect +riented 'rogramming
A point in space
Many points in space
Store in a variable
Data type
Organize te points in a particular fasion
an! !efine its accessing "ecanis"
Data Structure
#$% &' Array( )AM*DAM
+' List( Se,uential
A brief concept of AD-

describe ob/ect-oriented -rogramming as -rogramming


abstract data types and their relationshi-s
7
(1) as a basic conce-t for ob/ect-orientation
7
8hat is (1) by the 3ay6
An abstract data type (ADT) is characterized by the following properties:
1. It exports a type.
2. It exports a set of operations. This set is called interface.
. !perations of the interface are the one and only access "echanis" to
the type#s data str$ct$re. (%ncaps$lation)
&. Axio"s and preconditions define the application do"ain of the type.
Ob.ect/Oriente! Concepts

0n ob.ect/orientation( AD-s are referre! to


as classes

(n instance of a class is called an ob/ect

1our Principles

#ncapsulation

Abstraction

0neritance

Poly"orpis"
CS201, IITG

9/arne Strou-stru-5 the language:s creator


C++ 2as !esigne! to provi!e Si"ula3s facilities for progra"
organization togeter 2it C3s efficiency an! fle4ibility for
syste"s progra""ing.
;rom 'rof. Ste-hen (. $d3ards< 8eb site
CS201, IITG

9/arne Strou-stru-5 the language:s creator


C++ 2as !esigne! to provi!e Si"ula3s facilities for progra"
organization togeter 2it C3s efficiency an! fle4ibility for
syste"s progra""ing.
;rom 'rof. Ste-hen (. $d3ards< 8eb site
Simula =>
- first +b/ect +riented Language (++L"
- officially introduced by +le ?ohan 1ahl and @risten Nygaard
at the *;*' )# ! 8or&ing #onference on Simulation Languages
in Lysebu near +slo in May 19=>.
CS201, IITG

9/arne Strou-stru-5 the language:s creator


C++ 2as !esigne! to provi!e Si"ula3s facilities for progra"
organization togeter 2it C3s efficiency an! fle4ibility for
syste"s progra""ing.
;rom 'rof. Ste-hen (. $d3ards< 8eb site
8hat is #226
#22 is a general--ur-ose -rogramming language
3ith a bias to3ards systems -rogramming that

is a better #

su--orts data abstraction

su--orts ob/ect-oriented -rogramming

su--orts generic -rogramming


CS201, IITG
0s C a subset of C++5

*n the strict mathematical sense5 # isn<t a


subset of #22.

)here are -rograms that are 4alid # but not


4alid #22

Ao3e4er5 #22 su--orts e4ery -rogramming


techniBue su--orted by #

$4ery # -rogram can be 3ritten in essentially


the same 3ay in #22 3ith the same run-time
and s-ace efficiency.

)hus5 #22 is as much a su-erset of (NS* #


CS201, IITG
Our first C an! C++ Progra"
// my first program in C++
#include <iostream>
using namespace std;
int main ()
{
cout << "Hello World!";
return 0;
}
/* my first program in C */
#include <stdio.h>
int main ()
{
printf(Hello World!)";
return 0;
}
Hello World!
Hello World!
CS201, IITG
Our first C an! C++ Progra"
// my first program in C++
#include <iostream>
using namespace std;
int main ()
{
cout << "Hello World!";
return 0;
}
/* my first program in C */
#include <stdio.h>
int main ()
{
printf(Hello World!)";
return 0;
}
Hello World!
Hello World!
*n traditional c225
1. iostream.h
!. names-ace not reBuired
CS201, IITG
6ariable an! Data -ypes

int myCDariableE

char myFStr1:

*nt !my*1E

#har FNE char FFME

int brea78

car bool8

int case8
CS201, IITG
6ariable an! Data -ypes

int myCDariableE

char myFStr1:

*nt !my*1E

#har FNE char FFME

int brea78

car bool8

int case8
CS201, IITG
6ariable an! Data -ypes

int myCDariableE -- Neither s-aces nor -unctuation mar&s or symbols can


be -art of an identifier.

char myFStr1: -- +nly letters (a5..G5(5...H"5 digits (0515...9"" and single


underscore characters are 4alid.

*nt !my*1E -- *n addition5 4ariable identifiers al3ays ha4e to begin 3ith a


letter.

#har FNE char FFME )hey can also begin 3ith an underline character (F "

So"e reserve! 7ey2or!s

int brea78

car bool8

int case8
CS201, IITG
6ariable an! Data -ypes

int myCDariableE -- Neither s-aces nor -unctuation mar&s or symbols can


be -art of an identifier.

char myFStr1: -- +nly letters5 digits and single underscore characters are
4alid.

*nt !my*1E -- *n addition5 4ariable identifiers al3ays ha4e to begin 3ith a


letter.

#har FNE char FFME )hey can also begin 3ith an underline character (F "

So"e reserve! 7ey2or!s

int brea78

car bool8

int case8
*dentifier: a seBuence of one or
more letters5 digits or underscore
characters (F".
CS201, IITG
6ariable an! Data -ypes

So"e reserve! 7ey2or!s

asm5 auto5 bool5 brea&5 case5 catch5 char5 class5


const5 constFcast5 continue5 default5 delete5 do5
double5 dynamicFcast5 else5 enum5 eI-licit5 eI-ort5
eItern5 false5 float5 for5 friend5 goto5 if5 inline5 int5
long5 mutable5 names-ace5 ne35 o-erator5 -ri4ate5
-rotected5 -ublic5 register5 reinter-retFcast5 return5
short5 signed5 siGeof5 static5 staticFcast5 struct5
s3itch5 tem-late5 this5 thro35 true5 try5 ty-edef5
ty-eid5 ty-ename5 union5 unsigned5 using5 4irtual5
4oid5 4olatile5 3charFt5 3hile
CS201, IITG
9at are te !ata types
CS201, IITG
Scope of variables
Jinclude KiostreamL
using names-ace stdE
main("
M int iE
iN>E
M
int /E
/NiCOE
P
/Ni2%
cout KK /KKendlE
P
CS201, IITG
Scope of variables
Jinclude KiostreamL
using names-ace stdE
main("
M int iE
iN>E
M
int /E
/NiCOE
P
/Ni2%
cout KK /KKendlE
P
9at is te output5
CS201, IITG
0nitialization of variables

*nitialiGation in #

int a N 0E

0nitialization in C++ % Above + belo2

$I: int a (0"E


CS201, IITG
0nitialization of variables

*nitialiGation in #

int a N 0E

0nitialization in C++ % Above + belo2

$I: int a (0"E


CS201, IITG
0ntro!uction to strings

*n #5 string is an array of char

$I: char myNameQR N MSrahulTP

*n Memory5 myName

*n #225 string is a class

string myName N SrahulT

String sName N S&umarT

#out KK myName 2 sName

rahul&umar
r a h u l
r a h u l
SiGe("
9egin("
end("
CS201, IITG
Operators

0s a:b sa"e as a::b 5

Assign"ent ;:<

9at is te value of + =: > 5

)elational an! e,uality operators ; ::( =:( ?( @( ?:( @: <

9at are te values of A 5

A : ++A //// Arit"etic operators ; +( /( B( *( C <

A +: + /////Co"poun! assign"ent

;+:( /:( B:( *:( C:( ??:( @@:( D:(E:( F:<

(2N!5 aCN%

9at is te value of A: +@@&

Sift operations ;left sift ;@@<( rigt sift ;??<<


CS201, IITG
Operators

9at is te value of a ; a : ;b:A( b++<<5

Co""a Operator G e4ecute fro" left to rigt an! assign te last


CS201, IITG
Operators
CS201, IITG
Basic 0nput*Output

#once-t: *.+ o-erations act on streams


(seBuences" of (S#** characters

Dalid to use the same *.+ statements in #22 as


in #: printf, scanf, and others in stdio.h

#22 -ro4ides an alternati4e 3ith the ne3


stream in-ut.out-ut features: cin and cout

cin: Used for &eyboard in-ut (std::cin"

cout: Used for screen out-ut (std::cout"

9oth cin and cout are data ob/ects and are


defined by a classes
CS201, IITG
Basic 0nput*Output

#once-t: *.+ o-erations act on streams


(seBuences" of (S#** characters

Dalid to use the same *.+ statements in #22 as


in #: printf, scanf, and others in stdio.h

#22 -ro4ides an alternati4e 3ith the ne3


stream in-ut.out-ut features: cin and cout

cin: Used for &eyboard in-ut (std::cin"

cout: Used for screen out-ut (std::cout"

9oth cin and cout are data ob/ects and are


defined by a classes
#22 uses message -assing mechanism
to communicate bet3een ob/ects
CS201, IITG
9asic *n-ut.+ut-ut (contd."
CS201, IITG
9asic *n-ut.+ut-ut (contd."
CS201, IITG
Strea" 0*O Hea!ers

iostream V contains basic information reBuired


for all stream *.+ o-erations

fstream V used for -erforming file *.+ o-erations


CS201, IITG
A strea"

( flo3 of character

*ntermadiate Storage (9uffers": *+ to streams


goes through a buffer. #22 allo3s the
-rogrammer to change the default beha4iour of
the associated buffer

State: each stream is associated 3ith a state


indicating 4arious things li&e if an error has
occur or not
CS201, IITG
0O Class Heirarcy
CS201, IITG
0O Strea"

$Iam-le:

cin LL 4ariableE *s it different from a N O LL 16

cout KK 4ariableE

clog KK 4ariableE

buffered

cerr KK 4ariableE

Unbuffered and -rint the 4ariable immediately

KK (left-shift o-erator"

+4erloaded as stream insertion o-erator

LL (right-shift o-erator"

+4erloaded as stream eItraction o-erator


CS201, IITG
Control Structures

if and else

if (condition" statement

if (condition" statement1 else statement!


CS201, IITG
Control Structures ;Cont!'<

0teration structures ;loops<

)he 3hile loo-

3hile (eI-ression" statement


CS201, IITG
Control Structures ;Cont!'<

0teration structures ;loops<

)he do-3hile loo-

do statement 3hile (condition"E


CS201, IITG
Control Structures ;Cont!'<

0teration structures ;loops<

)he for loo-

for (initialiGationE conditionE increase" statementE


CS201, IITG
Control Structures

?um- statements

)he brea& statement


CS201, IITG
Control Structures

?um- statements

)he continue statement


CS201, IITG
Control Structures

?um- statements

)he goto statement


CS201, IITG
Control Structures

?um- statements

)he eIit function

4oid eIit (int eIitcode"E

)erminate the -rogram

$Iitcode 0: normal termination

+thers5 termination due to error or uneI-ected


results
CS201, IITG
Control Structures

?um- statements

S3itch
CS201, IITG
C++ Class
9or7 2it C++ Classes an! Ob.ects
Class :!ata + functions
#lass Structure
class classNameM
accessFs-ecifierF1:
membersE
accessFs-ecifierF!:
membersE
accessFs-ecifierF%:
membersE
WW.
P ob/ectNameE
(n access s-ecifier is one of the follo3ing
three
7-ri4ate: accessible 3ithin other members
of the same class and their friends.
7-rotected: accessible 3ithin other
members of the same class5 their friends
and deri4ed classes
7-ublic: accessible from any3here the
class is 4isible
71efault access s-ecifier is -ri4ate
$Iam-le
class aRectangleM
-ri4ate:
int IE
int yE
-ublic:
4oid setDalue(int5int"E
int area("E
P myRectE
(n access s-ecifier is one of the follo3ing
three
7-ri4ate: accessible 3ithin other members
of the same class and their friends.
7-rotected: accessible 3ithin other
members of the same class5 their friends
and deri4ed classes
7-ublic: accessible from any3here the
class is 4isible
71efault access s-ecifier is -ri4ate
$Iam-le
class aRectangleM
int IE
int yE
-ublic:
4oid setDalue(int a5int b"
M INaE yNbE
P
int area("
M return ICyE
P
PE
class aRectangleM
int IE
int yE
-ublic:
4oid setDalue(int5int"E
int area("E
PE
4oid aRectangle::setDalue(int a5 int b"
M INaE yNbE
P
int aRectangle::area("
M return ICyE
P
$Iam-le
class aRectangleM
int IE
int yE
-ublic:
4oid setDalue(int a5int b"
M INaE yNbE
P
int area("
M return ICyE
P
PE
int main("
M aRectangle aE
a.setDalue(!5O"E
cout KK S area :TKKa.area("E
return 0E
P
int main("
M aRectangle a5 bE
a.setDalue(!5O"E
cout KK Sarea of a:TKKa.area("E
b.setDalue(%5O"E
cout KK Sarea of b:TKKb.area("E
return 0E
P
! O
setDalue(int5int"
area("
% O
setDalue(int5int"
area("
a b
$Iam-le
#lass aRectangleM
int IE
int yE
-ublic:
4oid setDalue(int a5int b"
M INaE yNbE
P
int area("
M return ICyE
P
PE
int main("
M aRectangle aE
a.setDalue(!5O"E
cout KK S area :TKKa.area("E
return 0E
P
int main("
M aRectangle a5 bE
a.setDalue(!5O"E
cout KK Sarea of a:TKKa.area("E
b.setDalue(%5O"E
cout KK Sarea of b:TKKb.area("E
return 0E
P
! O
setDalue(int5int"
area("
% O
setDalue(int5int"
area("
#an 3e do a.IN10
data enca-sulation b
$Iam-le
class aRectangleM
int IE
int yE
-ublic:
4oid setDalue(int a5int b"
M INaE yNbE
P
int area("
M return ICyE
P
PE
int main("
M aRectangle aE
a.setDalue(!5O"E
cout KK S area :TKKa.area("E
return 0E
P
8hat if
a.setDalue(!5O"E
is before
cout KK S area :TKKa.area("E
$Iam-le
class aRectangleM
int IE
int yE
-ublic:
4oid setDalue(int a5int b"
M INaE yNbE
P
int area("
M return ICyE
P
PE
int main("
M aRectangle aE
a.setDalue(!5O"E
cout KK S area :TKKa.area("E
return 0E
P
8hat if
a.setDalue(!5O"E
is before
cout KK S area :TKKa.area("E
( mechanism to initialiGe
-arameters -- #onstructor
$Iam-le
class aRectangleM
int IE
int yE
-ublic:
4oid setDalue(int a5int b"
M INaE yNbE
P
int area("
M return ICyE
P
PE
int main("
M aRectangle aE
a.setDalue(!5O"E
cout KK S area :TKKa.area("E
return 0E
P
class aRectangleM
int IE
int yE
-ublic:
aRectangle(int a5int b"
M INaE yNbE
P
int area("
M return ICyE
P
PE
int main("
M aRectangle a(!5O"E
cout KK S area :TKKa.area("E
return 0E
P
#onstructor
#onstructor

( function that initialiGes the members of an


ob/ect

Same name as that of class

0t as
V
No return ty-e.
V
No return statement.

*t is used at the time of ob/ect creation.

#onstructors are ne4er virtual


#onstructor

( function that initialiGes the members of an


ob/ect

Same name as that of class

0t as
V
No return ty-e.
V
No return statement.

*t is used at the time of ob/ect creation.

#onstructors are ne4er virtual


class Foo
{
};
void function(Foo &arg)
{
}
int main()
{
Foo& f = Foo(); // error.
function(Foo()); // error
const Foo& f2 = Foo(); // OK
}
#onstructor )y-es
7 Default Constructor
V Constructor 2it no para"eters
V *f no constructor is defined in a class
7 ( default constructor is called
7 *t /ust allocates the memory s-ace and assigns the default 4alues (if any"
7 Overloa!ing Constructors
V Many constructors 3ith different -arameters
#onstructor )y-e
7 Default Constructor

*f no constructor is defined in a class

*t /ust allocates the memory s-ace and assigns the default 4alues (if
any"
7 Overloa!ing Constructors

Many constructors 3ith different -arameters


#lass aRectangleM
int IE
int yE
-ublic:
aRectangle("
M IN=E yN!E P
aRectangle(int a5int b"
M INaE yNbE
P
int area("
M return ICyE
P
PE
int main("
M aRectangle a(!5O"E
cout KK S area :T KK a.area("E
return 0E
P
#onstructor )y-e
7 Default Constructor
V Constructor 2it no para"eters

*f no constructor is defined in a class

1efault constructor is called

*t /ust allocates the memory s-ace and assigns the default 4alues (if any"
7 Overloa!ing Constructors

Many constructors 3ith different -arameters


7 Oter -ypes of constructors
V #o-y constructors: *nitialiGe an ob/ect by another ob/ect
V #on4ersion constructors: #on4ert from the ty-e of the argument to the
class ty-e.
1estructors
7
use to deallocate memory and cleanu- the resources for an
ob/ect and its members 3hen the ob/ect is destroyed.
7
call 3hen the ob/ect -asses out of sco-e or is eI-licitly deleted.
7
ta&es no arguments and has no return ty-e
7
*ts address cannot be ta&en.
7
1estructors cannot be declared const5 4olatile5 const 4olatile or
static.
7
( destructor can be declared 4irtual or -ure 4irtual.
1estructors
7
use to deallocate memory and cleanu- the resources for an
ob/ect and its members 3hen the ob/ect is destroyed.
7
call 3hen the ob/ect -asses out of sco-e or is eI-licitly deleted.
7
ta&es no arguments and has no return ty-e
7
*ts address cannot be ta&en.
7
1estructors cannot be declared const5 4olatile5 const 4olatile or
static.
7
( destructor can be declared 4irtual or -ure 4irtual.
#onst
-- const int #onstant1
-- const int C #onstant!

-- int const C #onstant!

-- int C const #onstant%
-- int const C const #onstantO
1estructors
7
use to deallocate memory and cleanu- the resources for an
ob/ect and its members 3hen the ob/ect is destroyed.
7
call 3hen the ob/ect -asses out of sco-e or is eI-licitly deleted.
7
ta&es no arguments and has no return ty-e
7
*ts address cannot be ta&en.
7
1estructors cannot be declared const5 4olatile5 const 4olatile or
static.
7
( destructor can be declared 4irtual or -ure 4irtual.
#onst
-- const int #onstant1N9=E
-- const int C #onstant!
declares that #onstant! is 4ariable -ointer to a constant integer
-- int const C #onstant!

-- int C const #onstant%
declares that #onstant% is constant -ointer to a 4ariable integer an
-- int const C const #onstantO
1estructors
7
use to deallocate memory and cleanu- the resources for an
ob/ect and its members 3hen the ob/ect is destroyed.
7
call 3hen the ob/ect -asses out of sco-e or is eI-licitly deleted.
7
ta&es no arguments and has no return ty-e
7
*ts address cannot be ta&en.
7
1estructors cannot be declared const5 4olatile5 const 4olatile or
static.
7
( destructor can be declared 4irtual or -ure 4irtual.
#lass aRectangleM
int IE
int yE
-ublic:
aRectangle("
M IN=E yN!E P
aRectangle(int a5int b"
M INaE yNbE
P
0aRectangle("M P
int area("
M return ICyE
P
PE
int main("
M aRectangle a(!5O"E
cout KK S area :TKKa.area("E
return 0E
P
Before "oving furter( let us e4plore pointers
first
9e 2ill co"ebac7 2it "ore e4a"ples on
class in te ne4t class
8hat is a -ointer6
int x = 10;
int *p;
p = &x;
p gets the address of x in memory.
p
x 10
8hat is a -ointer6
int x = 10;
int *p;
p = &x;
*p = 20;
*p is the 4alue at the address p.
p
x 20
8hat is a -ointer6
int x = 10;
int *p = NULL;
p = &x;
*p = 20;
1eclares a -ointer
to an integer
& is a!!ress o-erator
gets address of I
* !ereference o-erator
gets 4alue at p
(llocating memory using ne2
Point *p = new Point(5, 5);

ne2 allocates s-ace to hold the ob/ect.

ne2 calls the ob/ect:s constructor.

ne2 returns a -ointer to that ob/ect.


1eallocating memory using !elete
// allocate memory
Point *p = new Point(5, 5);

// !ree t"e memory


#elete p;
;or e4ery call to new5 there must be
eIactly one call to #elete
Using ne2 3ith arrays
int x = 10;
int* n$m%1 = new int&10'; // o(
int* n$m%2 = new int&x'; // o(

*nitialiGes an array of 10 integers on the hea-.

#22 eBui4alent of the follo3ing # code


int* n$m% = (int*)malloc(x * %i)eo!(int));
Using ne2 3ith multidimensional arrays
int x = *, y = +;
int** n$m%* = new int&x'&+';// o(
int** n$m%+ = new int&x'&y';// ,-./

*nitialiGes a multidimensional array

+nly the first dimension can be a 4ariable. )he rest


must be constants.

Use single dimension arrays to fa&e multidimensional


ones
Using !elete on arrays
// allocate memory
int* n$m%1 = new int&10';
int* n$m%* = new int&x'&+'&5';

// !ree t"e memory


#elete&' n$m%1;
#elete&' n$m%*;

Aa4e to use #elete&''


;e3 Buestions6
class (
M int IE
-ublic:
4oid dis-lay("M cout KK I KKendlE P
PE
main("
M ( aE
a.dis-lay("E
( bN(("E
b.dis-lay("E
P
class (
M static int IE
-ublic:
4oid dis-lay("M cout KK I KKendlE P
PE
main("
M ( aE
a.dis-lay("E
P
class (
M static const int IN1!E
-ublic:
4oid dis-lay("M cout KK I KKendlE P
PE
main("
M ( aE
a.dis-lay("E
P
class (
M const int IE
-ublic:
4oid dis-lay("M cout KK I KKendlE P
PE
main("
M ( aE
a.dis-lay("E
P
;e3 Buestions6
class (
M int IE
-ublic:
((int a"M INaE P
4oid dis-lay("M cout KK I KKendlE P
PE
main("
M ( aE
a.dis-lay("E
P
class (
M int IE
-ublic:
((int aN!0"M INaE P
4oid dis-lay("M cout KK I KKendlE P
PE
main("
M ( aE
a.dis-lay("E
P
class (
M int IE
-ublic:
((int aN!0"M INaE P
4oid dis-lay("M cout KK I KKendlE P
PE
main("
M ( aE
a.dis-lay("E
P
ty-edef class (
M int IE
-ublic:
4oid 9("M IN10EP
(("M IN!0E P
4oid dis-lay("M cout KK I KKendlE P
P9E
main("
M 9 aE
a.dis-lay("E
P

Class Allocation
7
Li7e Static an! Dyna"ic allocation in C( C+
+ also support static an! !yna"ic
allocation

#lass allocations

Static allocation

aRectangle a(%5X"E

Aea- allocation (dynamic"

aRectangle CbE

bN ne3 aRectangle(%5X"E

Copy Constructor

#reate an ob/ect as a co-y of another ob/ect

ReBuired 3hen

'ass an ob/ect as a -arameter to a function


7
'ass by 4alue

Return an ob/ect from a function


7
Return by 4alue

(ssign a class to another

*f no co-y constructor is defined5 create a default co-y


constructor

#o-y the data members of the source ob/ect to the data


member of the target ob/ect

Copy Constructor
7
SyntaI

ta&es a reference to a const -arameter.

its first -arameter a (-ossibly const or 4olatile" reference to


its o3n class ty-e.

*f more than one argument5 the rest must ha4e default


4alues associated 3ith them.
V
Kclass nameL(const Kclass nameLY ob/ect5 W"E

aRactangle ( const aRactangle Y b5W "E



Copy Constructor
7
SyntaI

ta&es a reference to a const -arameter.

its first -arameter a (-ossibly const or 4olatile" reference to


its o3n class ty-e.

*f more than one argument5 the rest must ha4e default


4alues associated 3ith them.

Kclass nameL(const Kclass nameLY ob/ect5 W"E

aRactangle ( const aRactangle Y b5W "E


#4a"ples
7
$;const $D copy1ro"Me<8
7
$;const volatile $D copy1ro"Me<8
7
$;volatile $D copy1ro"Me<8
7
$;const $D copy1ro"Me( int : &H<8
7
$;const $D copy1ro"Me( !ouble : &'H( int : AH<8

Copy Constructor
7
#reate an ob/ect as a co-y of another ob/ect
7
ReBuired 3hen
V
'ass an ob/ect as a -arameter to a function
7
'ass by 4alue
V
Return an ob/ect from a function
7
Return by 4alue
V
(ssign a class to another
7
*f no co-y constructor is defined5 create a default co-y
constructor
V
#o-y the data members of the source ob/ect to the data
member of the target ob/ect
$Iam-le:
1. aRectangle a(!5O"E .. not a co-y constructor
!. aRectangle b(a"E .. a co-y constructor used a the time building an
ob/ect
%. aRectangle cNaE ..co-y constructor is used to initialiGe in
declaration.
O. aRectangle dE
dNaE .. (ssignment o-erator5 no constructor or co-y constructor.
X. my;unction(-"E .. co-y constructor in4ol4ed
=. dNmy+b/ectReturn;unction("E .. co-y constructor in4ol4ed

0"portance of Copy Constructors

0"portance of Copy Constructor
#lass aRectangleM
int C IE
int C yE
-ublic:
aRectangle("
M IN ne3 int(="E yN ne3 int(!"E P
aRectangle(int a5int b"
M IN ne3 int(a"E yNne3 int(b"E
P
int area("
M return (CI"C(Cy"E
P
PE
int main("
M aRectangle a(!5O"E
aRectangle b NaE
P
class a)ectangleI
int B 48
int B y8
public%
a)ectangle;<
I 4: ne2 int;J<8 y: ne2 int;+<8 K
a)ectangle;int a(int b<
I 4: ne2 int;a<8 y:ne2 int;b<8
K
int reset;int a( int b<
I B4:a8 By:b8 K
int area;< I return ;B4<B;By<8 K
K8
int "ain;<
I a)ectangle a;+(A<8
a)ectangle b :a8
cout @@ a'area;<@@ L M @@ b'area;<8
a'reset;+(&H<8
cout @@ a'area;<@@ L M @@ b'area;<8
K

0"portance of Copy Constructor
class a)ectangleI
int B 48
int B y8
public%
a)ectangle;<
I 4: ne2 int;J<8 y: ne2 int;+<8 K
a)ectangle;int a(int b<
I 4: ne2 int;a<8 y:ne2 int;b<8
K
int reset;int a( int b<
I B4:a8 By:b8 K
int area;< I return ;B4<B;By<8 K
K8
int "ain;<
I a)ectangle a;+(A<8
a)ectangle b :a8
cout @@ a'area;<@@ L M @@ b'area;<8
a'reset;+(&H<8
cout @@ a'area;<@@ L M @@ b'area;<8
K
int B4: ne2 int;J<
int B4: ne2 intNJO
Are te t2o !ifferent5

0"portance of Copy Constructor
class a)ectangleI
int B 48
int B y8
public%
a)ectangle;<
I 4: ne2 int;J<8 y: ne2 int;+<8 K
a)ectangle;int a(int b<
I 4: ne2 int;a<8 y:ne2 int;b<8
K
int reset;int a( int b<
I B4:a8 By:b8 K
int area;< I return ;B4<B;By<8 K
K8
int "ain;<
I a)ectangle a;+(A<8
a)ectangle b :a8
cout @@ a'area;<@@ L M @@ b'area;<8
a'reset;+(&H<8
cout @@ a'area;<@@ L M @@ b'area;<8
K



!0 !0

!0
+ut-ut6

0"portance of Copy Constructor
class a)ectangleI
int B 48
int B y8
public%
a)ectangle;<
I 4: ne2 int;J<8 y: ne2 int;+<8 K
a)ectangle;int a(int b<
I 4: ne2 int;a<8 y:ne2 int;b<8
K
int reset;int a( int b<
I B4:a8 By:b8 K
int area;< I return ;B4<B;By<8 K
K8
int "ain;<
I a)ectangle a;+(A<8
a)ectangle b :a8
cout @@ a'area;<@@ L M @@ b'area;<8
a'reset;+(&H<8
cout @@ a'area;<@@ L M @@ b'area;<8
K



!0 !0

!0
+ut-ut6
9en a)ectangle a;+(A< e4ecute!

!
O
I
y
a

0"portance of Copy Constructor
class a)ectangleI
int B 48
int B y8
public%
a)ectangle;<
I 4: ne2 int;J<8 y: ne2 int;+<8 K
a)ectangle;int a(int b<
I 4: ne2 int;a<8 y:ne2 int;b<8
K
int reset;int a( int b<
I B4:a8 By:b8 K
int area;< I return ;B4<B;By<8 K
K8
int "ain;<
I a)ectangle a;+(A<8
a)ectangle b :a8
cout @@ a'area;<@@ L M @@ b'area;<8
a'reset;+(&H<8
cout @@ a'area;<@@ L M @@ b'area;<8
K



!0 !0

!0
+ut-ut6
9en a)ectangle b:a e4ecute!

!
O
I
y
I
y
a
b

0"portance of Copy Constructor
class a)ectangleI
int B 48
int B y8
public%
a)ectangle;<
I 4: ne2 int;J<8 y: ne2 int;+<8 K
a)ectangle;int a(int b<
I 4: ne2 int;a<8 y:ne2 int;b<8
K
int reset;int a( int b<
I B4:a8 By:b8 K
int area;< I return ;B4<B;By<8 K
K8
int "ain;<
I a)ectangle a;+(A<8
a)ectangle b :a8
cout @@ a'area;<@@ L M @@ b'area;<8
a'reset;+(&H<8
cout @@ a'area;<@@ L M @@ b'area;<8
K



!0 !0

!0
+ut-ut6

0"portance of Copy Constructor
class a)ectangleI
int B 48
int B y8
public%
a)ectangle;<
I 4: ne2 int;J<8 y: ne2 int;+<8 K
a)ectangle;int a(int b<
I 4: ne2 int;a<8 y:ne2 int;b<8
K
int reset;int a( int b<
I B4:a8 By:b8 K
int area;< I return ;B4<B;By<8 K
K8
int "ain;<
I a)ectangle a;+(A<8
a)ectangle b :a8
cout @@ a'area;<@@ L M @@ b'area;<8
a'reset;+(&H<8
cout @@ a'area;<@@ L M @@ b'area;<8
K



!0 !0

!0
+ut-ut6
9en a)ectangle b:a e4ecute!

!
O
I
y
I
y
a
b
!
O

0"portance of Copy Constructor
class a)ectangleI
int B 48
int B y8
public%
a)ectangle;<
I 4: ne2 int;J<8 y: ne2 int;+<8 K
a)ectangle;int a(int b<
I 4: ne2 int;a<8 y:ne2 int;b<8 K
a)ectangle;const a)ectangle D a<
I 4: ne2 int;a'4<8 y: ne2 int;a'y<8 K
int reset;int a( int b< I B4:a8 By:b8 K
int area;< I return ;B4<B;By<8 K
K8
int "ain;<
I a)ectangle a;+(A<8
a)ectangle b :a8
cout @@ a'area;<@@ L M @@ b'area;<8
a'reset;+(&H<8
cout @@ a'area;<@@ L M @@ b'area;<8
K



!0 !0

!0
+ut-ut6

0"portance of Copy Constructor
class a)ectangleI
int B 48
int B y8
public%
a)ectangle;<
I 4: ne2 int;J<8 y: ne2 int;+<8 K
a)ectangle;int a(int b<
I 4: ne2 int;a<8 y:ne2 int;b<8 K
aRectangle(const aRectangle & a)
{ if(this != &a)
{ this->x= new int(a.x);
this->y= new int(a.y); }
}
int reset;int a( int b< I B4:a8 By:b8 K
int area;< I return ;B4<B;By<8 K
K8
int "ain;<
I a)ectangle a;+(A<8
a)ectangle b :a8
cout @@ a'area;<@@ L M @@ b'area;<8
a'reset;+(&H<8
cout @@ a'area;<@@ L M @@ b'area;<8
K
)he SthisT refers to
the ob/ect itself.

Conversion Constructor
7
$Iam-le
V
int a(!"E

string(ShelloT"E

double a N ! 2 %.XE

string b NShelloTE
V
(bo4e $Iam-les are im-licit con4ersion
V
*t in4ol4es a tem-orary ob/ect
V
double aN ! 2%.X
7 *t is eBui4alent to
V double tem- N(double" !
V double a Ntem- 2 %.X

Conversion Constructor

( constructor 3ith single -arameter of other


ty-e

)he com-iler uses this idiom as one 3ay to


infer con4ersion rules for a class.

#om-iler u-dates its ty-e con4ersion rules.



Proble" 2it Conversion Constructor
7
( constructor 3ith single -arameter of other
ty-e

)he com-iler uses this idiom as one 3ay to


infer con4ersion rules for a class.
class Data
I
public%
Data ;< ** Default constructor
I 4yz : PQn7no2nP8 K
Data ;const DataD a< ** Copy constructor
I R'' K
Data ;const stringD a< ** Convert constructor
I 4yz: a8 K
Data ;const carB a< ** Convert constructor
I 4yz: a8 K
Data ;int a< ** constructor
I R'' K
Data ;String a( int b< ** constructor
I R'' K
private%
string 4yz8
K8

Proble" 2it Conversion Constructor
7
( constructor 3ith single -arameter of other
ty-e

)he com-iler uses this idiom as one 3ay to


infer con4ersion rules for a class.
class Data
I
public%
Data ;< ** Default constructor
I 4yz : PQn7no2nP8 K
e4plicit Data ;const DataD a< ** Copy constructor
I R'' K
Data ;const stringD a< ** Convert constructor
I 4yz: a8 K
Data ;const carB a< ** Convert constructor
I 4yz: a8 K
e4plicit Data ;int a< ** constructor
I R'' K
Data ;String a( int b< ** constructor
I R'' K
private%
string 4yz8
K8

Data Me"ber 0nitialization

+nly through t3o mechanisms

#onstructor

aRectangle ((int a5 int b"E

Member initialiGer

aRectangle(": I(!"5y(O" M P

Member initialiGer reBuired in the follo3ing


cases

)o initialiGe const data members.

)o initialiGe references.

)o initialiGe member ob/ects.



#4a"ple
class Tas
{
!rivate"
int !id;
string name;
!u#lic"
Tas(int num$ const string & n)
{ !id=num;
name=n; }
void dis!la%(){cout && name&$endl;}
};
main()
{ Tas a('$()ello();
a.dis!la%();
}

#4a"ple
class Tas
{
!rivate"
int !id;
string name;
!u#lic"
Tas(int num)" name(*)ello()
{ !id=num;
}
void dis!la%(){cout && name&$endl;}
};
main()
{ Tas a(');
a.dis!la%();
}

1rien! functions an! Class

(ny private member inside a class


is not accessible from outside the
class.

( non-member function or an
eIternal class can ne4er access
the -ri4ate data.

9ut5 there may be cases 3here


non-member function or an
eIternal class need to access the
-ri4ate data

Solution: frien!
#lass aRectangleM
int IE
int yE
-ublic:
aRectangle("
M IN=E yN!E P
aRectangle(int a5int b"
M INaE yNbE
P
int area("
M return ICyE
P
PE
int main("
M aRectangle a(!5O"E
cout @@ L area@@ a'4Ba'y8
return 0E
P

1rien! 1unction

SyntaI:

frien! KreturnFty-eL QKclassFnameL %%O function ( args "E

;riend function is not a member function of the


class

( friend function has full access to -ri4ate and


-ublic member of a class.

( function can be a friend 3ith any number of


classes

0t is possible to !eclare te frien! function as eiter


private or public'

1rien! 1unction
class a)ectangleI
int 48
int y8
frien! voi! 2i!t;<8
frien! voi! aS,uare %% eigt;<8
public%
a)ectangle;< I 4:J8 y:+8 K
a)ectangle;int a(int b< I 4:a8 y:b8 K
Sa)ectangle;<I K
int area;< I return 4By8 K
K8
voi! 2i!t;<
I a)ectangle b8
cout @@ b'4 @@en!l8K
int "ain;<
I a)ectangle a;+(A<8
2i!t;<8
return H8
K
class aSBuareM
int IE
-ublic:
int height(aRectangle Y a"
M INa.IE
P
PE

1rien! class

SyntaI

friend Kclass nameLE

( class I can be declared as a friend of some


other class y

)he friend class I is not a member of y

)he member functions of y ha4e full access to


-ri4ate and -ublic members of I.

( class can be a friend 3ith any number of


classes

0t is possible to !eclare te frien! class as eiter


private or public'

1rien! class
class a)ectangleI
int 48
int y8
frien! class "y1rien!8
public%
a)ectangle;< I 4:J8 y:+8 K
a)ectangle;int a(int b< I 4:a8 y:b8 K
Sa)ectangle;<I K
int area;< I return 4By8 K
K8
class "y1rien!I
a)ectangle a8
public%
voi! "y1r!$;<I cout @@ a'4 @@en!l8 K
K8
int "ain;<
I "y1rien! b8
b'"y1r!$;<8
return H8
K

1rien! class
class a)ectangleI
int 48
int y8
frien! class "y1rien!8
public%
a)ectangle;< I 4:J8 y:+8 K
a)ectangle;int a(int b< I 4:a8 y:b8 K
Sa)ectangle;<I K
int area;< I return 4By8 K
K8
class "y1rien!I
a)ectangle a8
public%
voi! "y1r!$;<I cout @@ a'4 @@en!l8 K
K8
int "ain;<
I "y1rien! b8
b'"y1r!$;<8
return H8
K
out-ut6

1rien!

9/arne Stoustru- (the creator of #22"

Use friend 3ith good /udgment.

)he -ri4ate access modifier 3as created for a good


reason: enca-sulation and data security.

*n other 3ords5 don<t use ZfriendZ as a hac&er.



Overloa!ing

+4erloading ('olymor-hism"

more than one definition for a function name or an


o-erator in the same sco-e

;unction o4erloading

+4erload a function 3ith multi-le functionality

+-erator o4erloading

(llo3 an o-erator to a--ly on different format



1unction Overloa!ing
voi! A!!An!Display;int 4( int y<
I
cout@@P C++ -utorial / 0nteger result% P@@;4+y<8
K
voi! A!!An!Display;!ouble 4( !ouble y<
I
cout@@ P C++ -utorial / Double result% P@@;4+y<8
K
voi! A!!An!Display;float 4( float y<
I
cout@@ P C++ -utorial / float result% P@@;4+y<8
K
int A!!An!Display;int 4( int y<
I
cout@@P C++ -utorial / 0nteger result% P@@;4+y<8
return 4+y
K

0!entify te function by te signature

-e para"eters represent te signature



1unction Overloa!ing
voi! A!!An!Display;int 4( int y<
I
cout@@P C++ -utorial / 0nteger result% P@@;4+y<8
K
voi! A!!An!Display;!ouble 4( !ouble y<
I
cout@@ P C++ -utorial / Double result% P@@;4+y<8
K
voi! A!!An!Display;float 4( float y<
I
cout@@ P C++ -utorial / float result% P@@;4+y<8
K
int A!!An!Display;int 4( int y<
I
cout@@P C++ -utorial / 0nteger result% P@@;4+y<8
return 4+y
K

0!entify te function by te signature

-e para"eters represent te signature


Tot an overloa!ing
1unction
0t is illigal to !effer
only in return !ata
type

Operator Overloa!ing
delete[] new[] delete new [ ] ( )
-> -> ! -- "" ## && >= $=
!= == >>= $$= >> $$ #= &= %=
&= '= = -= "= > $ = !
( # & % & ' - "
Allo2s built/in operators for user !efine! type

Operator Overloa!ing
Uou can not overloa! tese operators
V
5% %% 'B '

Operator Overloa!ing

SyntaI:

Kreturn ty-eL o-erator KsymbolL (args" MW..P

$Iam-le

aRectangle aE

22aE

22(22a"E

aNbE

aN(cN(b2Nd""E

#4a"ple% unary
class a)ectangleI
int 48
int y8
public%
a)ectangle;< I 4:J8 y:+8 K
a)ectangle;int a(int b< I 4:a8 y:b8 K
Sa)ectangle;<I K
int area;< I return 4By8 K
voi! operator ++;<I ++ 48 ++y8 K
K8
int "ain;<
I "y1rien! b8
++b8 ++;++b<8
return H8
K

A nonstatic "e"ber function

returnWtype operatorX;<

A non"e"ber function

returnWtype operatorX;-<

#4a"ple% unary
class a)ectangleI
int 48
int y8
public%
a)ectangle;< I 4:J8 y:+8 K
a)ectangle;int a(int b< I 4:a8 y:b8 K
Sa)ectangle;<I K
int area;< I return 4By8 K
voi! operator ++;<I ++ 48 ++y8 K
K8
int "ain;<
I "y1rien! b8
++b8 ++;++b<8
return H8
K

A nonstatic "e"ber function

returnWtype operatorX;<

A non"e"ber function

returnWtype operatorX;-<
#omment6

#4a"ple% unary
class a)ectangleI
int 48
int y8
public%
a)ectangle;< I 4:J8 y:+8 K
a)ectangle;int a(int b< I 4:a8 y:b8 K
Sa)ectangle;<I K
int area;< I return 4By8 K
a)ectangle operator ++;<I ++ 48 ++y8 return BtisK
K8
int "ain;<
I "y1rien! b8
++;++b<8
cout @@ b'area;<8
return H8
K
+ut-ut6
!1 or %!

#4a"ple% unary
class a)ectangleI
int 48
int y8
public%
a)ectangle;< I 4:J8 y:+8 K
a)ectangle;int a(int b< I 4:a8 y:b8 K
Sa)ectangle;<I K
int area;< I return 4By8 K
K8
voi! operator ++;a)ectangle b<
I ++ b'48 ++b'y8 K
int "ain;<
I "y1rien! b8
++b8
return H8
K

A nonstatic "e"ber function

returnWtype operatorX;<

A non"e"ber function

returnWtype operatorX;-<
#omment6

#4a"ple% unary
class a)ectangleI
int 48
int y8
public%
a)ectangle;< I 4:J8 y:+8 K
a)ectangle;int a(int b< I 4:a8 y:b8 K
Sa)ectangle;<I K
int area;< I return 4By8 K
K8
voi! operator ++;a)ectangle b<
I ++ b'48 ++b'y8 K
int "ain;<
I "y1rien! b8
++b8
return H8
K

A nonstatic "e"ber function

returnWtype operatorX;<

A non"e"ber function

returnWtype operatorX;-<
+4erloading
should be a
friend function

#4a"ple% unary
class a)ectangleI
int 48
int y8
public%
a)ectangle;< I 4:J8 y:+8 K
a)ectangle;int a(int b< I 4:a8 y:b8 K
Sa)ectangle;<I K
int area;< I return 4By8 K
K8
voi! operator ++;a)ectangle b<
I ++ b'48 ++b'y8 K
int "ain;<
I "y1rien! b8
++b8
return H8
K

A nonstatic "e"ber function

returnWtype operatorX;<

A non"e"ber function

returnWtype operatorX;-<
Self Study:
-ostfiI increament
i.e.5 b22

#4a"ple% binary
class a)ectangleI
int 48
int y8
public%
a)ectangle;< I 4:J8 y:+8 K
a)ectangle;int a(int b< I 4:a8 y:b8 K
Sa)ectangle;<I K
int area;< I return 4By8 K
voi! operator +;a)ectangle b<
I 4:4+b'48 y:y+b'y8 K
K8
int "ain;<
I "y1rien! b(a8
a:a+b8
return H8
K

A nonstatic "e"ber function

returnWtype operatorX;Q<

A non"e"ber function

returnWtype operatorX;Q(-<

#4a"ple% binary
class a)ectangleI
int 48
int y8
public%
a)ectangle;< I 4:J8 y:+8 K
a)ectangle;int a(int b< I 4:a8 y:b8 K
Sa)ectangle;<I K
int area;< I return 4By8 K
voi! operator +;a)ectangle b<I 4:4+b'48 y:y+b'y8 K
K8
int "ain;<
I "y1rien! b(a8
a:a+b8
return H8
K
#omments6

#4a"ple% binary
class a)ectangleI
int 48
int y8
public%
a)ectangle;< I 4:J8 y:+8 K
a)ectangle;int a(int b< I 4:a8 y:b8 K
Sa)ectangle;<I K
int area;< I return 4By8 K
a)ectangle operator +;a)ectangle b<
I 4:4+b'48 y:y+b'y8
return Btis8
K
K8
int "ain;<
I "y1rien! b(a8
a:a+b8
return H8
K
Return

Self Stu!y%
Overloa!ing for oter operators

Class 0neritance
Dehicle
#ar 9us
SuGu&i
)ata

Class 0neritance
class ( M
-ri4ate:
int (FIE
-rotected:
int (FyE
-ublic:
4oid (Ff1("
PE
class 9 : -ublic ( M
-ri4ate:
int 9FIE
-rotected:
int 9FyE
-ublic:
4oid 9Ff1("E
PE
9ase #lass
1eri4e #lass

Class 0neritance
class ( M
-ri4ate:
int (FIE
-rotected:
int (FyE
-ublic:
4oid (Ff1("
PE
class 9 : -ublic ( M
-ri4ate:
int 9FIE
-rotected:
int 9FyE
-ublic:
4oid 9Ff1("E
PE
B is Pa 7in! of aP A
B is P!erive! fro"P A
B is Pa specialize!P A
B is a PsubclassP of A
B is a P!erive! classP of A
A is te Pbase classP of B
A is te PsuperclassP of B
0neritance is referre! to as
1eri4e classes inherites the
-rotected and -ublic members of
base class

Class 0neritance
class ( M
-ri4ate:
int (FIE
-rotected:
int (FyE
-ublic:
4oid (Ff1("
PE
class 9 : -ublic ( M
-ri4ate:
int 9FIE
-rotected:
int 9FyE
-ublic:
4oid 9Ff1("E
PE

public%

protecte! "e"bers are


inerite! as protecte! an!
public "e"bers are inerite! as
public "e"bers

private%

inerite! as private "e"bers

protecte!%

inerite! as protecte! "e"bers


Default ineritance is private
0neritance can be of

Class 0neritance
class ( M
-ri4ate:
int (FIE
-rotected:
int (FyE
-ublic:
((.."M..P
4oid (Ff1("
PE
class 9 : -ublic ( M
-ri4ate:
int 9FIE
-rotected:
int 9FyE
-ublic:
4oid 9Ff1("E
PE

constructors an! !estructors

Assign"ent operators i'e'( :;<

frien!s
9at can not be inerite!
9en 2e create an ob.ect of !erive! class

te base class constructor is calle! an!


ten te !erive! class constructor is calle!'

base class constructor initializes its !ata


"e"bers an! te !erive! class constructor
initializes te !erive! classes !ata
"e"bers'

by !efault( !efault constructor is calle!

Oter2ise( nee! to call initializer



Class 0neritance
class ( M
-ri4ate:
int (FIE
-rotected:
int (FyE
-ublic:
((int"M......P
4oid (Ff1("
PE
class 9 : -ublic ( M
-ri4ate:
int 9FIE
-rotected:
int 9FyE
-ublic:
9M....P
4oid 9Ff1("E
PE
$rror

Class 0neritance
class ( M
-ri4ate:
int (FIE
-rotected:
int (FyE
-ublic:
((int"M......P
4oid (Ff1("
PE
class 9 : -ublic ( M
-ri4ate:
int 9FIE
-rotected:
int 9FyE
-ublic:
9:((10"M....P
4oid 9Ff1("E
PE
*nitialiGe 9ase
#onstructor

Class 0neritance
class ( M
-ri4ate:
int (FIE
-rotected:
int (FyE
-ublic:
4oid (Ff1("
PE
class 9 : -ublic ( M
-ri4ate:
int 9FIE
-rotected:
int 9FyE
-ublic:
4oid 9Ff1("E
PE

Te2 !ata "e"bers

Te2 "e"ber functions

Te2 constructors an! !estructor

Te2 frien!s
9at can be a!!e! on !erive!
classes

Class 0neritance
class ( M
-ri4ate:
int (FIE
-rotected:
int (FyE
-ublic:
4oid (Ff1("
PE
class 9 : -ublic ( M
-ri4ate:
int 9FIE
-rotected:
int 9FyE
-ublic:
4oid 9Ff1("E
PE

call !estructor of te !erive! class

call !estructor of te base class


9at appen 2en a !erive!
class is !estroye!

A Class 0n Me"ory
class ( M
-ri4ate:
int (FIE
-rotected:
int (FyE
-ublic:
4oid (Ff1("
PE
class 9 : -ublic ( M
-ri4ate:
int 9FIE
-rotected:
int 9FyE
-ublic:

4oid 9Ff1("E
PE
( aE
int (FI
int (Fy

a contiguous region of "e"ory'

A pointer to te first byte of tat region of


"e"ory'

1ro" Me"ory
class ( M
-ri4ate:
int (FIE
-rotected:
int (FyE
-ublic:
4oid (Ff1("
PE
class 9 : -ublic ( M
-ri4ate:
int 9FIE
-rotected:
int 9FyE
-ublic:

4oid 9Ff1("E
PE
( aE
int (FI
int (Fy

a contiguous region of "e"ory'

A pointer to te first byte of tat region of


"e"ory'
To infor"ation
relate! to ;non/
virtual< "e"ber
functions is
place! in te
ob.ect

1ro" Me"ory
class ( M
-ri4ate:
int (FIE
-rotected:
int (FyE
-ublic:
4oid (Ff1("
PE
class 9 : -ublic ( M
-ri4ate:
int 9FIE
-rotected:
int 9FyE
-ublic:

4oid 9Ff1("E
PE
( aE
int (FI
int (Fy

a contiguous region of "e"ory'

A pointer to te first byte of tat region of


"e"ory'
Ho2 is te function AWf&;<
accesse! 5

1ro" Me"ory
class ( M
-ri4ate:
int (FIE
-rotected:
int (FyE
-ublic:
4oid (Ff1(int"
PE
class 9 : -ublic ( M
-ri4ate:
int 9FIE
-rotected:
int 9FyE
-ublic:

4oid 9Ff1("E
PE
( aE
int (FI
int (Fy

a contiguous region of "e"ory'

A pointer to te first byte of tat region of


"e"ory'
-e call to function AWf&;< is converte! to
an or!inary function call by te co"piler'
#4% A Bpt8
pt/?AWf&;&H<8
is converte! to
fWW1&A;pt(&H<8

1ro" Me"ory
class ( M
-ri4ate:
int (FIE
-rotected:
int (FyE
-ublic:
4oid (Ff1("
PE
class 9 : -ublic ( M
-ri4ate:
int 9FIE
-rotected:
int 9FyE
-ublic:

4oid 9Ff1("E
PE
( aE
int (FI
int (Fy

a contiguous region of "e"ory'

A pointer to te first byte of tat region of


"e"ory'
9 bE
int (Fy
int 9FI
int 9FI

1ro" Me"ory
class ( M
-ri4ate:
int (FIE
-rotected:
int (FyE
-ublic:
4oid (Ff1("
PE
class 9 : -ublic ( M
-ri4ate:
int 9FIE
-rotected:
int 9FyE
-ublic:

4oid 9Ff1("E
PE
( aE
int (FI
int (Fy

a contiguous region of "e"ory'

A pointer to te first byte of tat region of


"e"ory'
9 bE
int (FI
int (Fy
int 9FI
int 9FI
To ouse7eeping inforfor"ation
about ineretance'

Multiple 0neritance
class ( M
-ri4ate:
int (FIE
-rotected:
int (FyE
-ublic:
4oid (Ff1("
PE
class 9 : -ublic (5 -ublic # M
-ri4ate:
int 9FIE
-rotected:
int 9FyE
-ublic:
4oid 9Ff1("E
PE
class # M
-ri4ate:
int #FIE
-rotected:
int #FyE
-ublic:
4oid #Ff1("
PE

Multi level 0neritance
class ( M
-ri4ate:
int (FIE
-rotected:
int (FyE
-ublic:
4oid (Ff1("
PE
class 9 : -ublic ( M
-ri4ate:
int 9FIE
-rotected:
int 9FyE
-ublic:
4oid 9Ff1("E
PE class # : -ublic 9M
-ri4ate:
int #FIE
-rotected:
int #FyE
-ublic:
4oid #Ff1("
PE

class List I
int arrayN&HHO8
int count8
public%
List;<% count;H< IK
voi! 0nsert;int n< I arrayNcount++O:n8 K
int Yet;int i< I return arrayNiO8 K
int Size;< I return count8 K
K8
voi! ManipList;List list< I list'0nsert;&HH<8 list'0nsert;+HH<8 K
class -otalingList% public List I
int total8
public%
-otalingList;<% List;<( total;H< IK
voi! 0nsert;int n< I total +: n8 List%%0nsert;n<8 K
int Yet-otal;< I return total8 K K8
int "ain;< I
-otalingList list8
int 48
list'0nsert;&H<8
list'0nsert;Z<8
cout @@ list'Yet-otal;< @@ en!l8
ManipList;list<8
cout @@ list'Yet-otal;< @@ en!l8
for ;4:H8 4 @ list'Size;<8 4++<
cout @@ list'Yet;4< @@ [ [8
cout @@ en!l8
return H8K

class List I
int arrayN&HHO8
int count8
public%
List;<% count;H< IK
voi! 0nsert;int n< I arrayNcount++O:n8 K
int Yet;int i< I return arrayNiO8 K
int Size;< I return count8 K
K8
voi! ManipList;List list< I list'0nsert;&HH<8 list'0nsert;+HH<8 K
class -otalingList% public List I
int total8
public%
-otalingList;<% List;<( total;H< IK
voi! 0nsert;int n< I total +: n8 List%%0nsert;n<8 K
int Yet-otal;< I return total8 K K8
int "ain;< I
-otalingList list8
int 48
list'0nsert;&H<8
list'0nsert;Z<8
cout @@ list'Yet-otal;< @@ en!l8
ManipList;list<8
cout @@ list'Yet-otal;< @@ en!l8
for ;4:H8 4 @ list'Size;<8 4++<
cout @@ list'Yet;4< @@ [ [8
cout @@ en!l8
return H8K
1X
1X
10 X

class List I
int arrayN&HHO8
int count8
public%
List;<% count;H< IK
voi! 0nsert;int n< I arrayNcount++O:n8 K
int Yet;int i< I return arrayNiO8 K
int Size;< I return count8 K
K8
voi! ManipList;ListD list< I list'0nsert;&HH<8 list'0nsert;+HH<8 K
class -otalingList% public List I
int total8
public%
-otalingList;<% List;<( total;H< IK
voi! 0nsert;int n< I total +: n8 List%%0nsert;n<8 K
int Yet-otal;< I return total8 K K8
int "ain;< I
-otalingList list8
int 48
list'0nsert;&H<8
list'0nsert;Z<8
cout @@ list'Yet-otal;< @@ en!l8
ManipList;list<8
cout @@ list'Yet-otal;< @@ en!l8
for ;4:H8 4 @ list'Size;<8 4++<
cout @@ list'Yet;4< @@ [ [8
cout @@ en!l8
return H8K

class List I
int arrayN&HHO8
int count8
public%
List;<% count;H< IK
voi! 0nsert;int n< I arrayNcount++O:n8 K
int Yet;int i< I return arrayNiO8 K
int Size;< I return count8 K
K8
voi! ManipList;ListD list< I list'0nsert;&HH<8 list'0nsert;+HH<8 K
class -otalingList% public List I
int total8
public%
-otalingList;<% List;<( total;H< IK
voi! 0nsert;int n< I total +: n8 List%%0nsert;n<8 K
int Yet-otal;< I return total8 K K8
int "ain;< I
-otalingList list8
int 48
list'0nsert;&H<8
list'0nsert;Z<8
cout @@ list'Yet-otal;< @@ en!l8
ManipList;list<8
cout @@ list'Yet-otal;< @@ en!l8
for ;4:H8 4 @ list'Size;<8 4++<
cout @@ list'Yet;4< @@ [ [8
cout @@ en!l8
return H8K
1X
1X
10 X 100 !00

class List I
int arrayN&HHO8
int count8
public%
List;<% count;H< IK
virtual voi! 0nsert;int n< I arrayNcount++O:n8 K
int Yet;int i< I return arrayNiO8 K
int Size;< I return count8 K
K8
voi! ManipList;ListD list< I list'0nsert;&HH<8 list'0nsert;+HH<8 K
class -otalingList% public List I
int total8
public%
-otalingList;<% List;<( total;H< IK
voi! 0nsert;int n< I total +: n8 List%%0nsert;n<8 K
int Yet-otal;< I return total8 K K8
int "ain;< I
-otalingList list8
int 48
list'0nsert;&H<8
list'0nsert;Z<8
cout @@ list'Yet-otal;< @@ en!l8
ManipList;list<8
cout @@ list'Yet-otal;< @@ en!l8
for ;4:H8 4 @ list'Size;<8 4++<
cout @@ list'Yet;4< @@ [ [8
cout @@ en!l8
return H8K
1X
%1X
10 X 100 !00

6irtual 1unction

6irtual function is a "e"ber function of a class tat is


!eclare! using te 7ey2or! PvirtualP'

A pointer to a !erive! class ob.ect "ay be assigne! to a


base class pointer

an! a virtual function calle! troug te pointer'


f;<
f;<
f;<
Call tis function
But actually e4ecute tis or tat

6irtual 1unction
class ( M
-ri4ate:
int (FIE
-rotected:
int (FyE
-ublic:
4irtual 4oid (Ff1("
PE
class 9 : -ublic ( M
-ri4ate:
int 9FIE
-rotected:
int 9FyE
-ublic:
4oid (Ff1("Mcout KK S9TEP
PE
int "ain;<I
B BtpB : ne2 B;<8
C BtpC : ne2 C;<8
A BptA : tpB8
ptA/?AWf&;<8
ptA : tpC8
ptA/?AWf&;<8
K
class # : -ublic ( M
-ri4ate:
int 9FIE
-rotected:
int 9FyE
-ublic:
4oid (Ff1("Mcout KK S#TEP
PE
Output%
B
C

0n te "e"ory

#om-iler creates a 4irtual table for each class


containing 4irtual function.

)he 4-table consists of addresses to the 4irtual


functions for classes and -ointers to the
functions from each of the ob/ects of the deri4ed
class.

8hene4er there is a function call made to the


4irtual function5 the 4-table is used to resol4e to
the function address.

1ynamic binding ha--ens during a 4irtual


function call

6irtual 1unction
class ( M
-ri4ate:
int (FIE
-rotected:
int (FyE
-ublic:
4irtual 4oid (Ff1("
PE
class 9 : -ublic ( M
-ri4ate:
int 9FIE
-rotected:
int 9FyE
-ublic:
4oid (Ff1("Mcout KK S9TEP
PE
B BtpB : ne2 B;<8
C BtpC : ne2 C;<8
A BptA : tpB8
ptA/?AWf&;<8
ptA : tpC8
ptA/?AWf&;<8
class 9 : -ublic ( M
-ri4ate:
int 9FIE
-rotected:
int 9FyE
-ublic:
4oid (Ff1("Mcout KK S#TEP
PE
Output%
B
C
Self Stu!y
9at is a!vantage an! !isa!vantages
of virtual "acine5

6irtual 1unction

'ure 4irtual function

$4ery deri4ed class should ha4e a definition

4irtual 4oid functionFname(" N 0E

(bstract class

act as eI-ressions of general conce-ts from 3hich


more s-ecific classes can be deri4ed.

one cannot create an ob/ect of an abstract class


ty-e

can use -ointers and references to abstract class


ty-es.

( class that contains at least one -ure 4irtual


function is considered an abstract class

6irtual 1unction
class ( M
-ri4ate:
int (FIE
-rotected:
int (FyE
-ublic:
4irtual int (Ff0("
Mreturn 0EP
4irtual 4oid (Ff1("N0
M cout KK S(TEP
PE
class 9 : -ublic ( M
-ri4ate:
int 9FIE
-rotected:
int 9FyE
-ublic:
4oid (Ff1("Mcout KK S9TEP
PE
A a8
a'AWfH;<

class # : -ublic ( M
-ri4ate:
int 9FIE
-rotected:
int 9FyE
-ublic:
4oid #Ff1("Mcout KK S#TEP
PE

6irtual 1unction
class ( M
-ri4ate:
int (FIE
-rotected:
int (FyE
-ublic:
4irtual int (Ff0("
Mreturn 0EP
4irtual 4oid (Ff1("N0
M cout KK S(TEP
PE
class 9 : -ublic ( M
-ri4ate:
int 9FIE
-rotected:
int 9FyE
-ublic:
4oid (Ff1("Mcout KK S9TEP
PE
A a8
a'AWfH;<

class # : -ublic ( M
-ri4ate:
int 9FIE
-rotected:
int 9FyE
-ublic:
4oid #Ff1("Mcout KK S#TEP
PE
#rror5

6irtual 1unction
class ( M
-ri4ate:
int (FIE
-rotected:
int (FyE
-ublic:
4irtual int (Ff0("
Mreturn 0EP
4irtual 4oid (Ff1("N0
M cout KK S(TEP
PE
class 9 : -ublic ( M
-ri4ate:
int 9FIE
-rotected:
int 9FyE
-ublic:
4oid (Ff1("Mcout KK S9TEP
PE
A a8
a'AWfH;<

class # : -ublic ( M
-ri4ate:
int 9FIE
-rotected:
int 9FyE
-ublic:
4oid #Ff1("Mcout KK S#TEP
PE
pure soul!
not ave
!efn'

6irtual 1unction
class ( M
-ri4ate:
int (FIE
-rotected:
int (FyE
-ublic:
4irtual int (Ff0("
Mreturn 0EP
4irtual 4oid (Ff1("N0
M cout KK S(TEP
PE
class 9 : -ublic ( M
-ri4ate:
int 9FIE
-rotected:
int 9FyE
-ublic:
4oid (Ff1("Mcout KK S9TEP
PE
A a8
a'AWfH;<

class # : -ublic ( M
-ri4ate:
int 9FIE
-rotected:
int 9FyE
-ublic:
4oid #Ff1("Mcout KK S#TEP
PE
To !efinition
of AWf&;<

6irtual 1unction
class ( M
-ri4ate:
int (FIE
-rotected:
int (FyE
-ublic:
4irtual int (Ff0("
Mreturn 0EP
4irtual 4oid (Ff1("N0
M cout KK S(TEP
PE
class 9 : -ublic ( M
-ri4ate:
int 9FIE
-rotected:
int 9FyE
-ublic:
4oid (Ff1("Mcout KK S9TEP
PE
A a8
a'AWfH;<

class # : -ublic ( M
-ri4ate:
int 9FIE
-rotected:
int 9FyE
-ublic:
4oid #Ff1("Mcout KK S#TEP
PE
To instantiation
of abstract
Class

class Account I
public%
Account; !ouble ! < I Wbalance : !8 K
virtual !ouble YetBalance;< I return Wbalance8 K
virtual voi! PrintBalance;< I cout@@Pbal% P@@YetBalance;< @@ en!l8 K
private%
!ouble Wbalance8
K8
class Cec7ingAccount % public Account I
public%
Cec7ingAccount;!ouble !< % Account;!< IK
voi! PrintBalance;< I cout@@Pbal% P@@YetBalance;< @@ en!l8 K
K8
class SavingsAccount % public Account I
public%
SavingsAccount;!ouble !< % Account;!< IK
voi! PrintBalance;< I cout@@Pbal% P@@YetBalance;< @@ en!l8 K
K8
int "ain;< I
Cec7ingAccount BpCec7ing : ne2 Cec7ingAccount; +HH'HH < 8
SavingsAccount BpSavings : ne2 SavingsAccount; +AH'HH <8
Account BpAccount : pCec7ing8
pAccount/?PrintBalance;<8
pAccount : pSavings8
pAccount/?PrintBalance;<8
K

-e"plates
Before -e"plate( see te follo2ing e4a"ple
9e ave a function to a!! t2o !ouble nu"bers
!ouble a!!;!ouble a( !ouble b<I
return a+b8
K
9e also nee! functions for t2o int nu"bers( ten 2e nee!
anoter function
int a!!;int a( int b<I
return a+b8
K
Or( say 2e ave an array of int( an! 2e also 2ant to use it for
storing array of car

-e"plates
Before -e"plate( see te follo2ing e4a"ple
9e ave a function to a!! t2o !ouble nu"bers
!ouble a!!;!ouble a( !ouble b<I
return a+b8
K
9e also nee! functions for t2o int nu"bers( ten 2e nee!
anoter function
int a!!;int a( int b<I
return a+b8
K
Or( say 2e ave an array of int( an! 2e also 2ant to use it for
storing array of car
Soln% -e"plates

-e"plates

( mechanism to generaliGe the dataty-e

Ael- us to 3rite code 3ithout being tied to


-articular ty-e.

)em-late can be of t3o ty-es

)em-late class : generaliGe the class ty-e

tem-late Kclass )L

class aRectangleMP

)em-late function : generaliGe the ty-es in a


function

tem-late Kclass )L

) add() a5 ) b"

M return a2bEP

Class -e"plate

a regular class definition 3ith the &ey3ord


tem-late as -refiI

SyntaI:

tem-late Kclass )L class Kclass nameL M PE


te"plate @class -?
class a)ectangleI
- 48
- y8
public%
voi! set6alue;- a(- b<
I 4:a8 y:b8
K
- area;<
I return 4By8
K
K8
class a)ectangleI
int 48
int y8
public%
voi! set6alue;int a(int b<
I 4:a8 y:b8
K
int area;<
I return 4By8
K
K8

te"plate @class -?
class a)ectangleI
- 48
- y8
public%
voi! set6alue;- a(- b<8
- area;<8
K8
te"plate @class -? voi!
a)ectangle @-?%%set6alue;- a(- b<
I 4:a8 y:b8
K
te"plate @class -? -
a)ectangle @-?%%area;<
I return 4By8
K
int "ain;<
I a)ectangle @int? a8
a'set6alue;+(A<8
cout @@ L area %M@@a'area;<8
return H8
K
int "ain;<
I type!ef a)ectangle@int? 0nt)ec8
0nt)ec a8
a'set6alue;+(A<8
cout @@ L area %M@@a'area;<8
return H8
K

te"plate @class -?
class a)ectangleI
- 48
- y8
public%
voi! set6alue;- a(- b<8
- area;<8
K8
te"plate @class -? voi!
a)ectangle @-?%%set6alue;- a(- b<
I 4:a8 y:b8
K
te"plate @class -? -
a)ectangle @-?%%area;<
I return 4By8
K
int "ain;<
I a)ectangle @int? a8
a'set6alue;+(A<8
cout @@ L area %M@@a'area;<8
return H8
K
int "ain;<
I type!ef a)ectangle@int? 0nt)ec8
0nt)ec a8
a'set6alue;+(A<8
cout @@ L area %M@@a'area;<8
return H8
K
- is 7no2n as te -e"plate
Para"eter

-e"plate Para"eters

)hree ty-es

)y-e tem-late -arameters

dataty-e

Non-ty-e tem-late -arameters

integral or enumeration

-ointer to ob/ect or -ointer to function

reference to ob/ect or reference to function

-ointer to member

)em-late tem-late -arameters

( tem-late as the -arameter of another tem-late



-ypena"e

*n the abo4e eIam-les5 3e used Kclass )L

*t is a generaliGed format.

*f the tem-late -arameter is a ty-e -arameter5


then Kclass )L is same as Kty-ename )L

Kty-ename )L indicates that tem-late


-arameter is ty-e

Usage:

Use the &ey3ord ty-ename if you ha4e a Bualified


name that refers to a ty-e and de-ends on a
tem-late -arameter.

$I: standard dataty-es.



Ta"e Bin!ing

)he -rocess of finding the declaration for each


name that is eI-licitly or im-licitly used in a
tem-late.

)he com-iler may bind a name in the definition


of a tem-late5 or it may bind a name at the
instantiation of a tem-late.
te"plate @class -?
class a)ectangleI
- 48
- y8
int z8
public%
voi! set6alue;- a(- b<
I 4:a8 y:b8 K
- area;<
I return 4By8 K
K8

-e 4 an! y are boun! at te ti"e of


te"plate instantiation

te z is boun! at te ti"e te"plate


!efinition

Depen!ent Ta"e

( de-endent name is a name that de-ends on


the ty-e or the 4alue of a tem-late -arameter.

;or eIam-le:
te"plate@class -? class Q % A@-?
I
-%%B 48
voi! f;A@-?D y<
I
By++8
K
K8

Depen!ent na"es are%

te base class A@-?

te typena"e -%%B

te variable y'

Depen!ent Ta"e

( de-endent name is a name that de-ends on


the ty-e or the 4alue of a tem-late -arameter.

;or eIam-le:
te"plate@class -? class Q % A@-?
I
-%%B 48 **//;a"biguous<///
voi! f;A@-?D y<
I
By++8
K
K8
-e co"piler bin!s !epen!ent na"es 2en a te"plate is instantiate!'
-e co"piler bin!s non/!epen!ent na"es 2en a te"plate is !efine!'
A ,ualifie! !epen!ent na"e suc as
-%%4 can be%
B A nontype ;ob.ect or function<
B A type
B A te"plate
By !efault( a ,ualifie! !epen!ent
na"e is a nontype

Depen!ent Ta"e

( de-endent name is a name that de-ends on


the ty-e or the 4alue of a tem-late -arameter.

;or eIam-le:
te"plate@class -? class Q % A@-?
I
typena"e -%%B 48
voi! f;A@-?D y<
I
By++8
K
K8
-e co"piler bin!s !epen!ent na"es 2en a te"plate is instantiate!'
-e co"piler bin!s non/!epen!ent na"es 2en a te"plate is !efine!'
A ,ualifie! !epen!ent na"e suc as
-%%4 can be%
B A nontype ;ob.ect or function<
B A type
B A te"plate
By !efault( a ,ualifie! !epen!ent
na"e is a nontype

1unction -e"plates

im-lemented as regular functions 3ith the


-refiIed &ey3ord tem-late

SyntaI:

tem-late Kclass )L Kreturn ty-eLKfunction nameL


(K-arameter listL" M... P
te"plate @class -?
- "a4;- a( - b<
I
return a ? b 5 a % b 8
K
voi! "ain;<
I

cout @@ P"a4;&H( &Z< : P @@ "a4;&H( &Z< @@ en!l 8
cout @@ P"a4;[7[( [s[< : P @@ "a4;[7[( [s[< @@ en!l 8
cout @@ P"a4;&H'&( &Z'+< : P @@ "a4;&H'&( &Z'+< @@ en!l 8
K

Class -e"plate Specialization

o4erride the tem-late-generated code by


-ro4iding s-ecial definitions for s-ecific ty-es.
te"plate @class -? class strea"
I
public%
voi! f;< I cout @@ Pstrea"@-?%%f;<P@@ en!l 8K
K 8
te"plate @? class strea" @car?
I
public%
voi! f;< I cout @@ Pstrea"@car?%%f;<P@@ en!l 8K
K 8
int "ain;<
I
strea"@int? si 8
strea"@car? sc 8
si'f;< 8
sc'f;< 8
return H 8
K
Output%
strea"@-?%%f;<
strea"@car?%%f;<

-e"plate Class Partial
Specialization

generate a s-ecialiGation of the class for /ust


one -arameter
te"plate @typena"e -&( typena"e -+?
class $
I K 8
**partial specialization
te"plate@typena"e -&?
class $@-&( int?
I
K 8
int "ain;<
I ** generates an instantiation fro" te base te"plate
$@car( car? 4cc 8
**generates an instantiation fro" te partial specialization
$@car( int? 4ii 8
return H 8
K

-e"plate 1unction Specialization

-ossible to o4erride the tem-late-generated


code by -ro4iding s-ecial definitions for s-ecific
ty-es
te"plate @class -?
- "a4;- a( - b<
I
return a ? b 5 a % b 8
K
int "ain;<
I
cout @@ "a4;&H( &Z< @@ en!l 8
cout @@ "a4;[7[( [s[< @@ en!l 8
cout @@ "a4;&H'&( &Z'+< @@ en!l 8
cout @@ "a4;PAla!!inP( P\as"ineP< @@ en!l 8
return H 8
K
Output
&Z
s
&Z'+
Ala!!in

te"plate @class -?
- "a4;- a( - b<
I
return a ? b 5 a % b 8
K
** Specialization of "a4 for carB
te"plate @?
carB "a4;carB a( carB b<
I
return strc"p;a( b< ? H 5 a % b 8
K
int "ain;<
I

cout @@ "a4;&H( &Z< @@ en!l 8
cout @@ "a4;[7[( [s[< @@ en!l 8
cout @@ "a4;&H'&( &Z'+< @@ en!l 8
cout @@ "a4;PAla!!inP( P\as"ineP< @@ en!l 8
return H 8
K

Static Me"bers an! 6ariables

$ach tem-late class or function generated from


a tem-late has its o3n co-ies of any static
4ariables or members.
tem-late Kclass )L
class [
M
-ublic:
static ) s E
P E
int main("
M
[ KintL Ii E
[ KcharCL Ic E
P

$ @int? as a static !ata "e"ber of type int

$ @carB? as a static !ata "e"ber s of type carB'



-e"plates an! 1rien!s

;riendshi- can be established bet3een a class


tem-late

and a global function

and a member function of another class (-ossibly a


tem-late class"

and class (-ossible tem-late class".



#4a"ples
te"plate @class -?
class a)ectangleI
- 48
- y8
public%
a)ectangle;< IK
a)ectangle;- a( - b<
I 4:a8 y:b8 K
- a!!;<
I return 4+y8 K
- "ulti;<
I return 4By8 K
K8
int "ain;<
I a)ectangle@int? a;+(Z<8
cout @@ a'a!!;<@@P P @@ a'"ulti;<8
K

#4a"ples
te"plate @class -?
class a)ectangleI
- 48
- y8
public%
a)ectangle;< IK
a)ectangle;- a( - b<
I 4:a8 y:b8 K
- a!!;<
I return 4+y8 K
- "ulti;<
I return 4By8 K
K8
int "ain;<
I a)ectangle@int? a;+(Z<8
cout @@ a'a!!;<@@P P @@ a'"ulti;<8
a)ectangle@string? a;LelloM(M2orl!M<8
cout @@ a'a!!;<@@P P @@ a'"ulti;<8
K

#4a"ples
te"plate @class -?
class a)ectangleI
- 48
- y8
public%
a)ectangle;< IK
a)ectangle;- a( - b<
I 4:a8 y:b8 K
- a!!;<
I return 4+y8 K
- "ulti;<
I return 4By8 K
K8
int "ain;<
I a)ectangle@int? a;+(Z<8
cout @@ a'a!!;<@@P P @@ a'"ulti;<8
a)ectangle@string? a;LelloM(M2orl!M<8
cout @@ a'a!!;<@@P P @@ a'"ulti;<8
K
To B overloa!ing for
string

#4a"ples
te"plate @class -?
class a)ectangleI
- 48
- y8
public%
a)ectangle;< IK
a)ectangle;- a( - b<
I 4:a8 y:b8 K
- a!!;<
I return 4+y8 K
- "ulti;<
I return 4By8 K
K8
int "ain;<
I a)ectangle@int? a;+(Z<8
cout @@ a'a!!;<@@P P @@ a'"ulti;<8
a)ectangle@string? a;LelloM(M2orl!M<8
cout @@ a'a!!;<@@P P @@ a'"ulti;<8
a)ectangle@const int? a8
cout @@ a'a!!;<@@P P @@ a'"ulti;<8
K

#4a"ples
te"plate @class -?
class a)ectangleI
- 48
- y8
public%
a)ectangle;< IK
a)ectangle;- a( - b<
I 4:a8 y:b8 K
- a!!;<
I return 4+y8 K
- "ulti;<
I return 4By8 K
K8
int "ain;<
I a)ectangle@int? a;+(Z<8
cout @@ a'a!!;<@@P P @@ a'"ulti;<8
a)ectangle@string? a;LelloM(M2orl!M<8
cout @@ a'a!!;<@@P P @@ a'"ulti;<8
a)ectangle@const int? a8
cout @@ a'a!!;<@@P P @@ a'"ulti;<8
K
To initializer for const
"e"ber in te
constructor

#4a"ples
te"plate @class -?
class a)ectangleI
- 48
- y8
public%
a)ectangle;< IK
a)ectangle;- a( - b<
I 4:a8 y:b8 K
- a!!;<
I return 4+y8 K
- "ulti;<
I return 4By8 K
K8
int "ain;<
I a)ectangle@int? a;+(Z<8
cout @@ a'a!!;<@@P P @@ a'"ulti;<8
a)ectangle@string? a;LelloM(M2orl!M<8
cout @@ a'a!!;<@@P P @@ a'"ulti;<8
a)ectangle@const int? a8
cout @@ a'a!!;<@@P P @@ a'"ulti;<8
a)ectangle@int? 4(y8
a)ectangle@a)ectangle @int? ? a8
cout @@ a'a!!;<@@P P @@ a'"ulti;<8
K
To + an! B overloa!ing
for a)ectangle

-ype -e"plates !o not e4cept

Local classes name and enumarations

)y-es that in4ol4e unnamed class ty-es or


unnamed enumaration ty-es
te"plate @typena"e -? class AI'''K8
type!ef struct I
!ouble 4( y( z8
K Point8
type!ef enu" Ire!(green(blueK BColorPtr8
int "ain;<I
struct Association
I int Bp8
int B,8
K8
A @Association B?error&8 **#rror% local type
A @ColorPtr? error+8 **#rror% unna"e type in te"plate argu"ent
A @Point? o78 ** Qnna"e! class type na"e! troug a type!ef
K

Ton/type -e"plates

Non-ty-e tem-altes -arameters are the r4alue


substitution ty-e

(nother nonty-e tem-late -arameter that has the


right ty-e

( com-ile-time constant 4alue of integer (or


enumeration" ty-e.

)he name of an eIternal 4ariable or function


-receded by the built-in unary Y o-erator

)he -re4ious &ind of argument but 3ithout a leading


Y o-erator is a 4alid argument for a nonty-e
-arameter of reference ty-e

( -ointer to member constant



#4a"ples

Non-ty-e tem-late -arameters that are declared


as arrays or functions are con4erted to -ointers
or -ointers to functions5 res-ecti4ely.
te"plate@int aNAO? class A I ''''K8
te"plate@int f;int<? class B I''' K8
int i8
int g;int< I return H8K
A@Di? 48
B@Dg? y8
Di is !e!uce! to int B
Dg is !e!uce! to int ;B<;int<

te"plate @typena"e -( - nontypeWpara"?
class C8
C@int( >>?Bc&8 **integral type
int a8
C@intB( Da?B c+8 **a!!ress of an e4ternal variable
voi! f;<8
voi! f;int<8
C@voi! ;B<;int<( f?Bc>8 ** na"e of a function% overloa! resolution selects f;int<
class $ Iint n8 static bool b8K8
C@bool D( $%%b? BcA8 **static class "e"bers are acceptable variable an!
function na"es
C@int $%%B( D$%%n?B cZ8 ** an e4a"ple of a pointer to "e"ber constant
te"plate @typena"e -? voi! te"p&Wfunc;<8
C@voi! ;<(Dte"p&Wfunc@!ouble? ?BcJ8 **function te"plate instantiations are
functions too
Yeneral constraint of te"plate argu"ents is tat a co"piler or a lin7er "ust be able
to e4press teir value 2en te progra" is being built'
#4a"ple fro"% C++ te"plates
By Davi! 6an!evoor!e( Ticolai M' \osuttis

1ollo2ings are not vali! non/type
te"plate currently

Non--ointer constants

;loating -oint numbers

String literals

-e"plate -e"plate Para"eters

( )em-late 3ithin a tem-late


template <template<typename T, T*> class
Buf> class Lexer
{
static char storage[5];
Buf<char, Lexer<Buf>!!storage> "uf;
#
$;

-e"plate -e"plate Para"eters

)em-late tem-late -arameters are -laceholders


for class tem-lates. )hey are declared much
li&e class tem-lates5 but the &ey3ords struct
and union cannot be used:
te"plate @te"plate@typena"e $? class C? ** O]
voi! f;C@int?B p<8
te"plate @te"plate@typena"e $? struct C? ** #))O)% struct not vali! ere
voi! f;C@int?B p<8
te"plate @te"plate@typena"e $? union C? ** #))O)% union not vali! ere
voi! f;C@int?B p<8

Default -e"plate Argu"ents

tem-late -arameter can be eBui--ed 3ith a


default argument5 although it must match the
corres-onding -arameter

)he set of default tem-late arguments


accumulates o4er all declarations of a gi4en
tem-late.

*f one tem-late -arameter has a default


argument5 then all tem-late -arameters
follo3ing it must also ha4e default arguments.

Re-eatition is not allo3ed



Default -e"plate Argu"ents
template <typename T%, typename T&, typename T',
typename T( ) char, typename T5 ) char>
class *uintuple; ++ ,-
template <typename T%, typename T&, typename T' ) char,
typename T(, typename T5>
class *uintuple; ++ ,-! T( an. T5 alrea.y ha/e .efaults
template <typename T% ) char, typename T&, typename T',
typename T(, typename T5>
class *uintuple; ++ 011,1! T% cannot ha/e a .efault argument
++ "ecause T& .oesn2t ha/e a .efault
te"plate@class - : car? class $8
te"plate@class - : car? class $ I K8 **#rror% )epeatition

Ta"espace

Names-aces allo3 to grou- entities li&e


classes5 ob/ects and functions under a name.

)his 3ay the global sco-e can be di4ided in


sub-sco-es5 each one 3ith its o3n name.
-e for"at of na"espaces is%
na"espace i!entifier
I
entities
K

#4a"ples

#4a"ples

#4a"ples

Ta"espace alias
names-ace ne3Fname N currentFnameE

#4ceptions

$Ice-tions -ro4ide a 3ay to react to eIce-tional


circumstances (li&e runtime errors" in our
-rogram by transferring control to s-ecial
functions called handlers.
1or"at%
tryI
state"ets
''''
K
catc;argu"ents<
I
state"ents
''''
K

#4a"ples

#4ceptions

8e can chain multi-le handlers (catch


eI-ressions"5 each one 3ith a different
-arameter ty-e.

+nly the handler that matches its ty-e 3ith the


argument s-ecified in the thro3 statement is
eIecuted.

*f 3e use an elli-sis (..." as the -arameter of


catch5 that handler 3ill catch any eIce-tion no
matter 3hat the ty-e of the thro3 eIce-tion is.

#4a"ples
tryI
''''''''''
K
catc ;int para"<I''''K
catc ;car para"<I'''K
catc ;'''< I''''''''K

#4ception specifications

8hen declaring a function 3e can limit the


eIce-tion ty-e it might directly or indirectly
thro3 by a--ending a thro3 suffiI to the
function declaration
float "yfunction ;car para"< tro2 ;int<8
int "yfunction ;int para"< tro2;<8 ** no e4ceptions allo2e!
int "yfunction ;int para"<8 ** all e4ceptions allo2e!

Stan!ar! e4ceptions

#22 Standard library -ro4ides a base


eIce-tions class

)his class has

usual default and co-y constructors

o-erators

destructors

additional 4irtual member function called 3hat that


returns a null-terminated character seBuence (char
C" and that can be o4er3ritten in deri4ed classes to
contain some sort of descri-tion of the eIce-tion.

#4a"ples

Stan!ar! #4ceptions
try
I
int B "yarray: ne2 intN&HHHO8
K
catc ;ba!WallocD<
I
cout @@ P#rror allocating "e"ory'P @@ en!l8
K

-ype Cast

*m-licit

short a N 10E int bE b N aE

$I-licit

short a N 10E int bE b N (int" aE

dynamic

dynamicFcast can be used only 3ith -ointers and


references to ob/ects.

*ts -ur-ose is to ensure that the result of the ty-e


con4ersion is a 4alid com-lete ob/ect of the
reBuested class.

Run-)ime )y-e *nformation (R))*" to &ee- trac& of


dynamic ty-es.

#4a"ples
class CBase I K8
class CDerive!% public CBase I K8
CBase b8 CBaseB pb8
CDerive! !8 CDerive!B p!8
pb : !yna"icWcast@CBaseB?;D!<8 ** o7% !erive!/to/base
p! : !yna"icWcast@CDerive!B?;Db<8 ** 2rong% base/to/!erive!

-ype cast

Static cast

double dN%.1O1X9!=XE int i N staticFcastKintL(d"E

-erform con4ersions bet3een -ointers to related


classes5 not only from the deri4ed class to its base5
but also from a base class to its deri4ed.

reinter-retFcast

con4erts any -ointer ty-e to any other -ointer ty-e5


e4en of unrelated classes.
class CBase IK8
class CDerive!% public CBase IK8
CBase B a : ne2 CBase8
CDerive! B b : staticWcast@CDerive!B?;a<8
class A IK8
class B IK8
A Ba : ne2 A8
B Bb : reinterpretWcast@BB?;a<8

-ype cast

constFcast

-ype cast

ty-eid

ty-eid allo3s to chec& the ty-e of an eI-ression:



0nput*Output 2it files

ofstream: Stream class to 3rite on files

ifstream: Stream class to read from files

fstream: Stream class to both read and 3rite from.to


files.

Open a 1ile

Statement: o-en (filename5 mode"E


Default%
ofstrea"/////////ios%%out
ifstrea"////////?ios%%in
fstrea"/////////?ios%%outFios%%in

0nput*Output 2it files

closing a file

myfile.close("E

#hec&ing state flags

bad(": Returns true if a reading or 3riting o-eration


fails.

fail(": Returns true in the same cases as bad("5 but


also in the case that a format error ha--ens

eof(": Returns true if a file o-en for reading has


reached the end.

good(": it returns false in the same cases in 3hich


calling any of the -re4ious functions 3ould return
true.

So"e useful functions

tellg;<

te current position of te get strea" pointer

tellp;<

te current position of teput strea" pointer

see7g;<

allo2 us to cange te position of te get strea" pointers

see7g;<

allo2 us to cange te position of te put strea" pointers

rea!;<

rea! fro" a file

2rite;<

2rite to a file

)eferences
)he #22 'rogramming Language5 by 9. Stroustru-
'rogramming -- 'rinci-les and 'ractice Using #225
by 9. Stroustru-
)he 1esign and $4olution of #225 by 9. Stroustru-
1ata (bstraction and -roblem sol4ing 3ith #225 by
;ran& M. #arrano
#22 tem-lates
9y 1a4id Dande4oorde5 Nicolai M. ?osuttis
*9M(R" im-lementation of the # and #22
-rogramming languages (htt-:..-ublib.boulder.ibm.com. (htt-:..-ublib.boulder.ibm.com.
infocenter.com-hel-.44101.indeI./s-" infocenter.com-hel-.44101.indeI./s-"

)eferences

)he -hotos and some contents in this slide are


also collected from 'rof. Ste-hen (. $d3ards<
lecture slides

)he #22 Language )utorial5 by ?uan Souli\

* ha4e also ta&en hel- from se4eral online


sources 3hich * found through ,oogle search.
Ao3e4er5 * ha4e lost trac& of them. * beg -ardon
for missing their names in the reference list.

A!vance C++
Self Stu!y
S)L: Standard )em-late Library

You might also like