0% found this document useful (0 votes)
124 views

Object Oriented Programming

The document discusses object oriented programming and key concepts like classes, objects, encapsulation, inheritance and polymorphism. It provides examples of classes and objects in C++ and how they are used to bundle data and behaviors. It also covers streams in C++ for input/output and how cout and cin are used with the insertion and extraction operators << and >>.

Uploaded by

noddinggenius
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
124 views

Object Oriented Programming

The document discusses object oriented programming and key concepts like classes, objects, encapsulation, inheritance and polymorphism. It provides examples of classes and objects in C++ and how they are used to bundle data and behaviors. It also covers streams in C++ for input/output and how cout and cin are used with the insertion and extraction operators << and >>.

Uploaded by

noddinggenius
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 253

Object Oriented

Programming

1
Topics
 Introduction  Inline functions
 Class & Objects  References
 Streams in C++  Parameter passing mec
 Declarations and Defini hanisms
tions  Class in C++
 lvalue & rvalue  Static Data Members
 Function Prototyping  Function Overloading
 Default Function Argum  Constructor
ents  Friends

2
Topics
 Inheritance  Click here to topic
 Destructor
 Virtual Functions
 Operator Overloading
 Class Template
 Vectors
 Exception Handling

3
Introduction to Object
Orientation

4
Characteristics of Object Oriented
Programming

Abstraction

Encapsulation

Inheritance

Polymorphism

5
Abstraction
Who am I ?

 I treat patients
Doctor
 I have a stethoscope
 I wear white coat
This is Abstraction

Showing only the Essential Part

6
Abstraction
Real World Abstraction Object-Oriented
Programming

Properties Data
Entity

Operations Functions

Mapping real world entity to OOP

7
Abstraction
"A view of a problem that extracts the essential information relevant
to a particular purpose and ignores the remainder of the
information." - [IEEE, 1983]

 Abstraction specifies necessary and sufficient descriptions rather


than implementation details.

 Since the classes use the concept of data abstraction, they are
known as Abstract Data Types (ADT).

 Building up data types from the predefined data types is data


abstraction.

8
Characteristics of Object Oriented
Programming

Abstraction

Encapsulation

Inheritance

Polymorphism

9
Encapsulation

State

Class

Behavior

Bundling the data and functions into a unit

10
Encapsulation

• Hide implementation details


- Only expose the interface
- Change the implementation without affecting interface

Interface Implementation

11
Encapsulation
 Bundling of data and functions together into a single unit (class).

 The advantages of encapsulation are


 Data hiding
 Information hiding

 The data is not accessible outside, only the function that are
wrapped in the class can access it. This insulation of data is called
as data hiding.

 Hiding the implementation details of the wrapped functions from the


user is called as information hiding (Separating what is to be done
from how it is to be done).

Example: Driver may know how to use steering(how), but not the
steering mechanism(what).

12
Characteristics of Object Oriented
Programming

Abstraction

Encapsulation

Inheritance

Polymorphism

13
Inheritance
Generalization
Doctor

Is a Is a Specialization
Neurologist Surgeon

states “is a” Relationship

14
Characteristics of Object Oriented
Programming

Abstraction

Encapsulation

Inheritance

Polymorphism

15
Polymorphism
 Polymorphic: from the Greek for “many forms”

 Polymorphism means ability to take multiple or many


forms.

 In programming languages, polymorphism means that


same code / operation / object behaves differently in
different context.

 It provides a single interface to entities of different types.

16
Classes & Objects

17
Object

State
State

Behavior
Behavior

Identity
Identity
(Booch)

18
State
 The state of an object encompasses all of the
(static) properties of the object plus the
current (dynamic) values of each of these
properties
 A property is an inherent or distinctive
characteristic, trait, quality, or feature that
contribute to making an object uniquely that
object
 We will use the word attribute, or data
member, to refer to the state of an object
19
Behavior

 Behavior is how an object acts and reacts, in


terms of state changes and interactions with
other objects.
 An operation is some action that one object
performs upon another in order to elicit a
reaction.

20
Identity

 Identity is the property of an object that


distinguishes it from all other objects.

21
What is an object?

OBJECT

set of methods
Operations
internal state
Data

22
Class & Object
Class:

 Putting behaviours(functions) and attributes(data) together.

 A class does not exist in the memory of computer during


program execution.

Object:

 An instance of a class. There can be more than one instance


for a class.

Example : Writing material is a class. Pen and Pencil are


objects of the class.

23
Class & Object
Account
Account
acct_no
acct_no
name
name
balance
balance
withdraw()
withdraw()
deposit(
deposit())
Account:acct1 Account:acct2
431245
431245 431246
431246
Patrick
Patrick Meyer
Meyer
50567.78
50567.78 35567.78
35567.78

24
Class & Object

Class Object
 Class is a data type  Object is an instance
of class data type
 It is the prototype or  It is a container
model.
 It does not occupy  It occupies memory
memory.
 It is compile-time  It is run-time entity
entity

25
26
C++ : The History

 Bjarne Stroustrup developed C++ (originally named "C with


Classes") during the 1980s.

 The name C++ was coined by Rick Mascitti in 1983.

 Standard was ratified in 1998 as ISO/IEC 14882:1998

 New version of the standard (known informally as C++0x) is


being developed.

27
Streams in C++

28
Streams in C++
Input / Output Statements in C++
 Stream - is an inter-mediator between the I/O device and the
user.
 cin - predefined object for input stream.
 cout - predefined object for output stream.

 User should include the iostream.h.

Input Devices Output Devices

Input Stream Output Stream

Program

29
Streams for Input and Output
Bore
#include<stdio.h>
void main()
{ in C
printf(“Good Morning\n”);
}

#include<iostream.h>
void main()
{ in C++
cout<<“Good Morning\n”;
} Good Morning
 printf() is used in C

 Output operator is better than output function

30
Why << ?

 Assignment operator = a candidate !

 Input operator different from output operator

 cout=a=b means cout=(a=b)

 How about < and > ?

 << and >> are asymmetric not commonly used

31
Streams for Input and Output
Precedence of << is low

#include<iostream.h>
int main()
{
int a=1,b=2,c=3;
cout<<“a*b+c=“<< a*b+c<<‘\n’;
}

Output:
5

32
Streams for Input and Output

 Parentheses must be used when operator of


lower precedence available
#include<iostream.h>
int main()
{
int a=1,b=2,c=3;
cout<<“a^b/c =“<<(a^b/c)<<‘\n’;
}
Output:
1

33
Streams for Input and Output

 Left shift operator << can be used in an


output statement but it must appear within
parentheses

#include<iostream.h>
void main()
{
int a=1,b=2; Output:
cout<<“a<<b=“<<(a<<b)<<‘\n’; 4
}

34
Streams for Input and Output
C++ associates set of manipulators with the output
stream

#include<iostream.h>
void main()
{
int amount=123;
Output:
cout<<dec<<amount<<‘\n ‘
<<oct<<amount<<‘\n ’ 123
<<hex<<amount;
} 173
7b

35
Streams for Input and Output
The stream cin is used for input

>> extraction operator (get from)

#include<iostream.h>
void main()
{
int amount;
cout<<“Enter the amount…\n”;
cin>>amount;
cout<<“The amount you entered was “;
cout<<amount; Enter the amount…
} 10
The amount you entered was 10
C++ sends the value that you enter to the variable amount

36
Comments

C++ comments is token // sequence. Wherever this


sequence appears (unless it is inside a string), everything
to the end of the current line is a comment
void main()
// I am a single line comment --- I am very useful…
/* *******we are multi line comments
we too are very useful********** */

37
Declarations and
Definitions

38
Declarations

 Before any identifier can be used in a C++


program it must be declared

 i.e. Its type must be specified to inform the


compiler what kind of entity the name refers to

39
Declarations -Examples
char ch;
int count=1;
char* name=“NUTS”;
struct complex{float re,im;};
complex cvar;
extern complex sqrt(complex); (not defined)
extern int error_number; (not defined)
typedef complex point;
float real(complex* p) { return p->re;};
const double pi=3.141592653589;
struct user;(not defined)

40
Definition
 There must be exactly one definition for each name in
a C++ program.

int count;
int count; error

Definition allocates appropriate memory.

Some definition specify a “value” for the entities they


define
int sum=0;

For types, functions and constants the value is permanent. For


non constant data types the initial value may be changed later.

41
Declarations Vs Definition

 Declarations
 It can be done more than once
 Tells the compiler about the entity type and name
 Definition
 It can be done only ones
 Allocates memory for the variable

For automatic and register variables, there is no


difference between definition and declaration.

42
Scope
 A declaration introduces a scope

 A declaration of a name in a block can hide a declaration in an


enclosing block or a global name

int x; Global x
void f()
{
int x; Local x
x=1; Assign to Local X
{
int x; Hides local x
x=2; Assign to Second local X
}
Assign to first local X
x=3;
}

int *p=&x; //take address of global X


43
Scope
#include<iostream.h>
int amount=456; Global scope
void main()
{
int amount=123; Local scope (function)
cout<<::amount;
cout<<‘\n’;
cout<<amount;
} Output:
456
:: unary scope resolution operator
123

44
Lifetimes of Data Object
 The lifetime of a data object is the time that it remains in existence
during the execution of the program

Scope Vs Lifetime

 Identifier has a scope i.e. the part of the program in which it can
be referenced ( or active).

 Data object has a lifetime i.e. the time it remains in existence


(period of time that a variable is assigned memory).

 A data object is a region of memory in which a value can be


stored it is characterized by its address, names (if any) type and its
value.

45
lvalue and rvalue

46
lvalue (location value)
 lvalue is an expression referring to an object or
function.

 lvalue is modifiable if it is not a function name, an


array name or constant.

 If E is an expression of pointer type the *E is an


lvalue referring to the object E points

E.g..
n=1; rvalue

lvalue
47
lvalue Vs rvalue

 In assignment operation
3 = n;
Is wrong because the left-hand side should be a
lvalue
Numeric literals, such as 3 and 3.14159, are
rvalues.

48
lvalue Vs rvalue
 An identifier that refers to an object is an lvalue, but
an identifier that names an enumeration constant is
an rvalue. For example:
enum color { red, green, blue };
color c;
...
c = green;    // ok
blue = green;    // error
The second assignment is an error because blue is an
rvalue.

49
lvalue Vs rvalue
 Although you can't use an rvalue as an lvalue, you can
use an lvalue as an rvalue. For example, given:
int m, n;
You can assign the value in n to the object designated by
m using:
m = n;
This assignment uses the lvalue expression n as an
rvalue.
 Strictly speaking, a compiler performs what the C++
Standard calls an lvalue-to-rvalue conversion to obtain
the value stored in the object to which n refers.

50
Function Prototyping

51
Function Prototyping
 ANSI C allows function prototyping

 borrowed from C++

 the return value, function name and number and type of


arguments can be specified in the function prototype, right
before main()

 While ANSI C allows function prototyping C++ requires


it.

void swap(int&,int&); Function prototyping must in C++

52
Function Prototyping
#include<iostream.h>
Function
void main()
Prototype
{
Scope of the
void show();
function is within
show(); main()
}
void show()
{
cout<<“Welcome to C++\n”; Actual Definition
} Output:
Welcome to C++

53
Function Prototyping
#include<iostream.h>

void main()
{
void f();
void show();
f(); Scope Problem
}
void f()
{
show();
}
void show()
{
cout<<“Welcome to C++\n”;
}

54
Default Function
Arguments

55
Default Function Arguments
A C++ function can have default values for some of the parameters

#include<iostream.h>
void function_2(int i,int j=2); Function Prototype
main(void)
{ Default value for j
int i=1;
int j=5;
function_2(i,j);
function_2(j);
} output:
void function_2(int i,int j) Actual Definition i is 1
{ cout<<“i is “<<i<<‘\n’; j is 5
cout<<“j is “<<j<<‘\n’;
}
i is 5
j is 2
Default values should be specified in function prototype56
Default Function Arguments

What happens if j is initialized at the time that function is called???

#include<iostream.h>
void function_2(int i,int j=2);
main(void)
{
int i=1;
int j;
function_2(i,j=8);
}
void function_2(int i,int j)
{ cout<<“i is “<<i<<‘\n’; output:
cout<<“j is “<<j<<‘\n’;
} i is 1
j is 8
57
Default Function Arguments
#include<iostream.h>
void function_2(int i,int j=2);
main(void)
{
int i;
function_2(i);
}
void function_2(int i,int j=8)
{ cout<<“i is “<<i<<‘\n’;
cout<<“j is “<<j<<‘\n’;
}

Error: previously specified default argument cannot be


changed in the function

58
Default Function Arguments
#include<iostream.h>
void function_2(int i=1,int j, int k=2);
main(void)
{
int i,k; No default value
int j=2;
function_2(i,j,k);
}
void function_2(int i, int j, int k)
{ cout<<“i is “<<i<<‘\n’;
cout<<“j is “<<j<<‘\n’;
cout<<“k is “<<k<<‘\n’;
} Rule: Only the last
arguments in a parameter
Error: Default value missing list can be initialized.
59
Default Function Arguments
#include<iostream.h>
void function_2(int i,int j=2,k=3);
main(void)
{
int i,k;
int j=2;
function_2(i,j,k);
}
void function_2(int i, int j, int k)
{ cout<<“i is “<<i<<‘\n’;
cout<<“j is “<<j<<‘\n’;
cout<<“k is “<<k<<‘\n’; output:
} i is 1
j is 2
k is 3
60
Default Function Arguments
#include<iostream.h>
void show (int =1,float =2.3, long =4);
void main()
{
show();
show(5);
show(6,7.8);
show(9,10.11,12L);
}
void show(int first, float second, long third)
{
cout<<“first = “<<first<<‘\n’; Rule: You cant omit an
cout<<“second = “<<second<<‘\n’; argument unless you
cout<<“third is “<<third<<‘\n’; omit all the arguments to
}
the right
61
Default Function Arguments

 Default values provides flexibility

 Functions called with same arguments can be given default values

#include<iostream.h>
void print(int value, int base=10);
void main()
{
print(31):
print(31,10)
print(31,16)
print(31,2);
}

62
Inline functions

63
Inline functions
 C++ provides inline keyword

 A new copy of the function to be inserted in each place


it is called

 Inline reduces the overhead of a function calls

 Program becomes larger

 Unlike macros they have type checking rules and


scope

64
double old_a;
#define DBL(a) ((old_a=a),((a)+(a))) Macro
inline int dbl(int a) {old_a=a; return a+a;} Inline function
void f(int* pi, char *pc)
{
double old_a=7;
old_a=dbl(*pi++);
old_a=dbl(pc);//error argument type mismatch
}

correct call will expand something like


int tmp;
old_a=((tmp=*pi++),(::old_a=tmp), (tmp+tmp)
to ensure the argument expression is evaluated only once

65
void f(int* pi, char *pc)
{
double old_a=7;
old_a=DBL(*pi++);
old_a=DBL(pc);//error in expansion
}

macro expands to
void f(int* pi, char *pc)
{
double old_a=7; // hides the global ‘old_a’
old_a=((old_a=*pi++),((*pi++)+(*pi++)));
old_a= ((old_a=pc),((pc)+(pc)));
}

Two errors
1) Adding pointers
2) Assigning char* to double

66
Inline Vs Macros

Inline Macros
Part of language Difficult to debug
easy to debug
Not always Always Expanded
expanded
Has type checking Does not have these
rules and scope
Compile time Preprocessing

67
References

68
References
 A reference is an alternative name for an object

 It is an ‘alias’

 The unary operator & with typename identifies a


reference.

 The notation X& means reference to X


int i=1;
int &r=i;// r and i refer to the same int
int x=r; //x=1
r=2;//i=2

 A reference must be initialized.

69
Reference

Despite appearance, no operator operates on a


reference.

int ii=0;
int &rr=ii;
rr++; // ii is incremented

The value of a reference can not be changed after


initialization.

It always refers to the object it was initialized.

70
References
#include<iostream.h>
void main()
{
int actualint=123;
int &otherint=actualint;
cout<<‘\n’<<actualint;
cout<<‘\n’<<otherint;
otherint++;
cout<<‘\n’<<actualint;
output:
cout<<‘\n’<<otherint; 123
actualint++; 123
cout<<‘\n’<<actualint; 124
cout<<‘\n’<<otherint; 124
}
125
Otherint refers to actualint 125
71
Initializing a Reference

Reference should be initialized with explicitly giving it


something to refer to.

Some Exceptions

You need not initialize a reference when


 it is declared with extern
 it is a member of a class
 it is declared as a parameter
 in a function declaration or definition
 it is declared as a return type of a function

72
Reference to an object of different type

double dval=3.14159;
const int &Ir=100;
const int &Ia=dval
const double &dr=dval+1.0

A const reference can be initialized to an object of a


different type (provided there is a conversion from one type
to the other) as well as to non-addressable values such as
literal const
For non-const reference, the same initialization are
not legal.

73
In the case of non-addressable values such as literal
const and objects of a different type, to accomplish this
the compilers must generate a temporary object that the
reference actually addresses but that the user has no
access to it.

74
References and Pointers

References can be viewed as pointers without usual


dereferencing notation.
int actualint=123;
int *const intptr=&actualint;

intptr is a constant pointer, one cannot make it point to


another integer once it has been initialized to actualint.
same is true for references.

75
References and Pointers

 References can’t be manipulated like pointers

 They don’t have pointer arithmetic

 They directly act on the object they refer to.

 With pointers, one can use the const keyword to


declare constant pointers and pointers to constant

76
Reference to constant

One can declare a reference to a constant


int actualint=123;
const int& otherint=actualint;

This makes otherint a readonly alias for actualint. You can’t


make any modification to otherint, only to actualint

But one cannot declare a constant reference


int &const otherint=actualint;//error
meaningless all references are constant by definition

77
Parameter passing
mechanisms

78
Parameter passing mechanisms

 Call by value

 Call by address

 Call by reference (in C++)

79
Parameter passing mechanisms
 Call by Value:
Value of actual argument is passed to formal argument.
Changes made in the formal arguments are local to the block of
called function, it does not affect the actual arguments.
void swap (int, int); //prototype
main( )
{ int x=4,y=5;
cout<<“x=“<<x<<“ y=“<<y; output: x=4 y=5
swap (x, y); //x, y actual args
cout<<“x=“<<x<<“ y=“<<y; output: x=4 y=5
}
void swap (int a, int b) //a, b formal args
{
int k;
k=a; a=b; b=k;
}

80
Parameter passing mechanisms
 Call by Address:
Instead of passing values, address is passed. Hence changes made in the formal arguments are reflected in the actual arguments.

void swap (int*, int*); //prototype


main( )
{ int x=4,y=5;
cout<<“x=“<<x<<“ y=“<<y; output: x=4 y=5
swap (&x, &y);
cout<<“x=“<<x<<“ y=“<<y; output: x=5 y=4
}

void swap (int* a, int* b)


{
int k;
k=*a; *a=*b; *b=k;
}

81
Parameter passing mechanisms
 Call by Reference:
In C++ it is possible to pass arguments by reference also. When we
pass arguments by reference, the ‘formal’ arguments in the function
become aliases to the ‘actual’ arguments in the calling function.

void swap (int&, int&); //prototype


main( )
{ int x=4,y=5;
cout<<“x=“<<x<<“ y=“<<y; output: x=4 y=5
swap (x, y);
cout<<“x=“<<x<<“ y=“<<y; output: x=5 y=4
}
void swap (int &a, int &b)
{
int k;
k=a; a=b; b=k;
}

82
References as Function Parameter
#include<iostream.h>
struct bigone
{int serno;
char text[1000];
}
bo={123,”This is a big structure”};
void valfunc(bigone v1); Pass by value
void ptrfunc(const bigone *p1); Pass by address
void reffunc(const bigone &r1);
Pass by reference
void main()
{
valfunc(bo);
ptrfunc(&bo);
reffunc(bo);
}

83
void valfunc(bigone v1)
{
cout<<‘\n’<<v1.serno;
cout<<‘\n’<<v1.text;
}
void ptrfunc(const bigone *p1)
{
cout<<‘\n’<<p1->serno;
cout<<‘\n’<<p1->text;
}
void valfunc(const bigone &r1)
{
cout<<‘\n’<<r1.serno;
cout<<‘\n’<<r1.text;
}
The reference function cannot modify the b0 variable. reffunc’s
parameter is a reference to a constant (readonly)

84
References as Return values
Reference can also be used to return values from a function.

int mynum=0;
int &num();
int &num() {return mynum;}
void main()
{
int i;
i=num();
num()=5;
}

return value of the num() is a reference initialized with the global


variable mynum. The expression num() acts as an alias for mynum.
i.e. a function call appear on the receiving end of an assignment
statement.

85
Reference as return values
int& rmax(int &m,int &n)
{
if(m>=n)
return m;
else
return n;
}

This function returns a reference to m or n rather than the


value of m or n
since rmax(i,j) yields a reference rmax(i,j)=0 is possible.

86
Initialization of a reference is trivial when the
initializer is an lvalue
The initializer of a plain T must be a lvalue or
even of type T
int num=10;
double &val=66.6; // not a lvalue
Compile time errors
double &post=num; // diff data type

87
Returning Reference from function
A function which return reference can also be used as lvalue.
#include<iostream.h>
int &f();
int x;
main()
{
f()=100;
cout<<x<<‘\n’;
return 0;
}

88
int &f()
{
return x; // not the value of the global variable x but the address
of x in reference form.
}

The statement f()=100;


puts the value 100 into x
int &f()
{
int x;
return x;
}
x is local the object one refers to does not go out of scope

89
int &f()
.
.
.
int *x;
x=f();

A reference returned by a function cannot be


assigned to a pointer

Reference are similar to pointers, but they are not


pointers.

An independent reference can refer to a constant.


const int &ref=100; // valid

90
Class in C++

91
Class declaration

Class declaration syntax :

class class-name
{
data-member declarations;
member-function declarations or definitions;
};

 Member function can be defined either inside or outside the class.

Syntax to define the member function outside the class:

return-type classname::function-name(argument list)


{ …… };

92
Class Example
class account
{ void main()
private: { account a1,a2;
int acc_no; a1.read();
char name[25]; a2.read();
float balance; a1.withdraw(1000);
public: a2.deposit();
void read() }
{ cin>>acc_no>>name>>balance; }
void withdraw(float amt) // member function defined inside a
class
{ balance-=amt; }
void deposit();
};
void account::deposit() // member function defined outside a class
{ float amt; // using binary scope resolution operator
cin>>amt;
balance += amt;
}

93
Access modifiers

Members can be declared as

 Private
visible only inside the class
 Protected
private + visible to the immediately derived class
 Public
globally visible

Note: The difference between the structure and class is the default
access specifier. In struct it is public, whereas in class it is private.

94
Array of objects
class player
{ char name[20];
int age; main()
public: {
void getdata(void); player cricket[3];
void putdata(void); cout<<“Enter name and age of 3 players”;
}; for (int i=0;i<3;i++)
void player::getdata(0 cricket[i].getdata();
{ for (int i=0;i<3;i++)
cout<<“\n Enter name: ”; cricket[i].putdata();
cin>>name; }
cout<<“\n Enter age: ”;
cin>>age;
}
void player::putdata(0
{
Name
age} cricket[0]
cout<<“\n Player name: ”<<name;
cout<<“\n Player age: ”;<<age; age}
Name cricket[1]

}
} Name
age cricket[2]

95
‘this’ pointer
 ‘this’ is the keyword can be used inside the class, which represents the
current object’s address.
 example:
class account
{
int acc_no;
public:
void assign(int acc) // void assign(int acc_no)
{ //{
acc_no=acc; // this->acc_no=acc_no;
} //}
};
 When a member function is called, it is automatically passed as an
implicit argument.

96
Introducing: const
void printSquare(const int& i)
{
i = i*i;
cout << i << endl; Cannot modify the reference i since it is
}
a constant
int main()
{
int i = 5; Won’t compile.
Math::printSquare(i);
}

97
Can also pass pointers to const

void printSquare(const int* pi)


{
*pi = (*pi) * (*pi);
cout << i << endl;
} pointer to a type constant int
int main()
{
int i = 5;
printSquare(&i);
} Still won’t compile.

98
Declaring things const

const River nile;

const River* nilePc;

River* const nileCp;

const River* const nileCpc


99
Read pointer declarations right to left

// A const River
const River nile;

// A pointer to a const River


const River* nilePc;

// A const pointer to a River


River* const nileCp;

// A const pointer to a const River


const River* const nileCpc

100
Static Data Members

101
Static Data Members
A “Static Data Member” is a single shared object to all objects of its class.

class SavingsAccount
{
public:  Each object is having its own
SavingsAccount(); copy of CurrentRate
void earnInterest();
{  Waste of space
total+=CurrentRate*total;
}  Has to update changes
private:
char name[30];  Inefficient
float total;
float CurrentRate;  Lead to Inconsistencies
};
Not Advisable

102
Why not Global Variable?

?
Scope
103
Every function will be able to modify its value

Requirement Solution

 Static Data Members have


 A Kind of Global variable
only one copy of it allocated
for an individual class
 No matter how many
 All objects of a particular
instances of the class
class access the same
variable
 Data Member made static by
prefixing with “static” keyword

104
Static Data Members
 Static Data members may seem like global variables, but
have class scope

Shared by all
objects

Ra
teo Object B
fI nt
= 0.5

Object A
cur_bal=5000 cur_bal=1500

105
Static Data Members
class SavingsAccount
{
public:
SavingsAccount();
void earnInterest();
{
total+=CurrentRate*total;
}
private:
char name[30];
float total;
static float CurrentRate;
};

106
Static Data Members
 A static member can be public, making visible to the rest of the
program
 If CurrentRate were a public member, one could access it as
follows :

void main()
{
SavingsAccount myaccount;
myaccount.CurrentRate = 0.050;
}

 It implies that only CurrentRate of myaccount is being modified

107
Static Data Members
 A static data member is initialized outside the class definition in
the same manner as a Non member variable.

 The only difference is that the class scope operator syntax


must be used.

void main()
{
float SavingsAccount::CurrentRate = 0.050;
}

108
Static Data Members
Only one initialization of a static data member can occur within a
program.

 Static member initializations should be placed in a file together with


the definitions of the inline member functions and not in the class
header file.
# include “savings.h”
float SavingsAccount::CurrentRate = 0.050;

SavingsAccount::SavingsAccount()
{
CurrentRate = 0.050;
// Cannot initialize a static member from within a constructor
// Because constructor may be called many times
}

109
 A static data member can appear as a default argument
to a member function of the class.

 A non static member cannot.

extern int a;
class foo
{
private:
int a;
static int b;
public:
int mem1(int = a); // ERROR.. There is no associated
class object
int mem2(int = b); // OK
int mem3(int = ::a); // OK
};

110
Static Data Members
 A static data member can be an object of the class
of which it is a member.

 A non static member is restricted to being declared as


a pointer or reference to an object of its class.

class Bar
{
public:
//…
private:
static Bar a;
Bar *b;
Bar c;
};

111
Static Member Functions
A “Static Member Function” is a member function that accesses only the
Static data members of a class.

class SavingsAccount
{
public:
SavingsAccount();
void earnInterest()
{ total+=CurrentRate*total; }
static void setinterest(float
new_value)
{ CurrentRate = new_value; }
private:
char name[30];
float total;
float CurrentRate;
};
112
Static Member Functions
 A static member function may be invoked through a class object
or a pointer to a class object similar to a non static member
function.

void main()
{
SavingsAccount myaccount;
myaccount.setinterest(0.50);
SavingsAccount::setinterest(0.50);
}

 A static member function does not contain a this pointer,


since a static member function doesn’t act on any particular instance
of the class.
 A static member function
 can’t access any of the class’s non static
 members or call any non static member functions

113
// Employ1.h Example Code
// Header File
# ifndef EMPLOY1_H
# define EMPLOY1_H
class Employee
{
public:
Employee(const char *,const char *) ;
~Employee();
char *getFirstName() const;
char *getLastName() const;
static int getcount();
private:
char * firstName;
char * lastName;
static int count;
};
# endif

114
# include<iostream.h>
# include<string.h> Contd…
# include<assert.h>
# include “Employ1.h”

int Employee :: count = 0;


int Employee :: getcount() { return count; }
Employee :: Employee(const char *first, const char *last)//constructor
{
firstName = new char [strlen(first)+1];
assert(firstName != 0);
strcpy(firstname,first);
lastName = new char[strlen(last)+1];
assert(lastName != 0);
strcpy(lastName,last);
++count;
cout<< “Employee Constructor for”
<< firstName
<< “ ”
<< lastName
<< “called.\n”;
}

115
Employee :: ~Employee() //destructor Contd…
{
cout << “~Employee() called for”
<< firstName << “ ” << lastName << endl;
delete firstName;
delete lastName;
}
char *Employee :: getFirstName() const
{
char *tempPtr = new char [strlen(firstName)+1];
assert(tempPtr != 0);
strcpy(tempPtr,firstName);
return tempPtr;
}
char *Employee :: getLastName() const
{
char *tempPtr = new char [strlen(lastName)+1];
assert(tempPtr != 0);
strcpy(tempPtr,lastName);
return tempPtr;
}

116
main()
{
clrscr();
cout << “Number of employees before instantiation is ”
<< Employee :: getcount() << endl;
Employee * e1Ptr = new Employee(“Sujan”,”Baker”);
Employee * e2Ptr = new Employee(“Roberts”,”Jones”);
cout << “Number of employees after instantiation is ”
<< e1Ptr -> getcount() << endl;
cout << “\nEmployee 1 : ” Output:
<< e1Ptr -> getFirstName() Number of employees before instantiation is
0
<< “ ” <<e1Ptr -> getLastName() Employee Constructor for Sujan Baker called
<< “\nEmployee 2 : ” Employee Constructor for Roberts Jones called
<< e2Ptr -> getFirstName() Number of employees before instantiation is
<< “ ” <<e2Ptr -> getLastName() 2Employee 1 : Sujan Baker
<< “\n\n”;
Employee 2 : Roberts Jones
delete e1ptr;
~Employee() called for Sujan Baker
delete e2Ptr; ~Employee() called for Roberts Jones
cout << “Number of employees after deletion
Number isof” employees after deletion is 0
<< Employee :: getcount() << endl;
return 0;
}
117
Function Overloading

118
Function Overloading
 When several different function declarations (signatures) are
specified for a single name in the same scope, that name is
said to be overloaded
 When that name is used, the correct function is selected by
comparing the types of the actual arguments with types of the
formal arguments

double abs(double);
int abs(double);
abs(1)//calls abs(int)
abs(1.0) // calls abs(double)

Function different only in return types cannot be overloaded

119
Function Overloading
Any type T, a T and a T& accept the same set of initializer
values, function with arguments types differing only in this
respect may not have the same name.

int f(int i)
{
//..
}
int f(int &r) // error; function types
//not sufficiently different
{
//..
}

120
Function Overloading
The following is possible

void f1(int);
void f2(int&);
void f3(const int&);
void g()
{
f1(2.2); //ok
f2(2.2); // error temporary needed
f3(2.2); //ok temporary used
}

such is applicable only for const references

121
Function Overloading
Example:
#include <iostream.h>

int square(int x) { return x * x; }


double square(double y) { return y * y; }

void main()
{
cout << "The square of integer 7 is " << square(7);
cout << "\nThe square of double 7.5 is " << square(7.5)
<< '\n';
}
The square of integer 7 is 49
The square of double 7.5 is 56.25

122
Function Overloading
 Passing constant values directly can also lead to ambiguity as
internal type conversions may take place.

Example: sum(int,int) and sum(float,float)

 The compiler will not be able to distinguish between the two calls
made below

sum(2,3);
sum(1.1, 2.2);

123
Constructor

124
Constructors
 Constructors are special member functions (should be declared in
public section) with the same name as the class. They do not return
values.

 The constructor is invoked whenever an object of its associated class is


created.

 A constructor is called whenever an object is defined or dynamically


allocated using the “new” operator.

 They are normally used to allocate memory for the data members and
initialize them.

 If no constructor is explicitly written then a default is created by the


compiler (not in the case of const and reference data members).

125
class Stack { Example
public:
Stack(int sz);
void Push(int value);
bool Full();
private:
int size;
int top;
int * stack;
};
Stack::Stack(int sz) {
size = sz;
Constructor
top = 0;
stack = new int[size];
}

126
Example

 To specify how an object is initialized we


write a constructor for it as a member
function.
 This member function has the same name as
the class name i.e, Stack().
 Stack(int) is the constructor in this example

127
Types of Constructors
 Default Constructor

 Parameterized Constructor

 Overloaded Constructor

 Constructor with Default Arguments

 Dynamic Constructor

 Copy Constructor

128
Default Constructor

 The constructor without arguments.


class sum
{
public:
int x, y;
sum();
};
sum::sum() Default Constructor
{
x=0;y=0;
}

129
Parameterized Constructors
 Parameters can be passed to the constructors
class sum
{ Parameterized
public: Constructor
int x, y;
sum(int i,int j);
};
sum::sum(int i,int j) Constructor called
{ implicitly
x=i;y=j;
}
void main( ) Explicit
{
sum s1(10,20);
sum s2 = sum(30,40); Object s1 x= 10 y= 20
cout<<"x= " << s1.x<<"y= "<<s1.y;
cout<<"x= " << s2.x<<"y= "<<s2.y;
Object s2 x= 30 y= 40
}

130
Overloaded Constructors
 Overloaded Constructors - Multiple constructors declared in a
class

 All constructors have different number of arguments

 Depending on the number of arguments, compiler executes


corresponding constructor
sum( ) {x=10;y=20;}; No arguments

sum (int, int) {x=i; y=j;}; Two arguments

131
Constructors with default arguments
 Constructors can be defined with default arguments

class sum
{
int x, y;
public:
void print()
{ cout<<“x = “<<x<<“y =“<<y; }
sum(int i, int j=10);
}; Default value for
j=10 (Used by the
sum::sum(int i,int j) object s1)
{ x=i;y=j; }
void main()
Object s1 x= 1 y= 10
{ sum s1(1),s2(8,9);
s1.print();
s2.print(); Object s2 x= 8 y= 9
}

132
Dynamic Constructor
 Allocates the right amount of memory during execution for each object
when the object’s data member size is not the same using new operator in
the constructor.
 The allocated memory should be released when the object is no longer
needed by delete operator in the destructor.

#include<string.h>
class String
{ char* data; void main()
public: {
String(const char* s = "") String s = "hello";
{ data = new char[20]; cout <<”s=”;
strcpy(data,s); } s.display( );
~String( ) String s1(“hello world”);
{ delete [ ] data; } cout<<”s1= ”;
void display() s1.display(); ss==hello
hello
{ cout << data; } s1=hello
} s1=helloworld
world
};

133
Copy Constructors
 Constructor that takes a reference to an object of the same class as
argument is Copy constructor. C++ calls a copy constructor (deep
copy or member-wise copy) to make a copy of an object.
 Copy constructor is invoked in any of the following three ways.
 When one object explicitly initializes another.

 sum s3=s1;
 When a copy of an object is made to be passed to a function.
 show(s2);
 When a temporary object is generated.
 s3=fun();
 If there is no copy constructor defined for the class, C++ uses the
default copy constructor which copies each data member, ie, makes a
shallow copy or bit-wise copy.

134
Copy Constructors
Syntax:
class_name(class_name &object_name) {…} //by reference is a must

class sum void main( )


{ { sum s1(10);
public: sum s2(s1);
int x; sum s3=s1;
sum( ){ } cout<<"\nx in s1= " << s1.x;
sum(int i) {x=i;} cout<<"\nx in s2= " << s2.x;
sum(sum &j) {x=j.x;} cout<<"\nx in s3= " << s3.x;
}; }

Objects s1 s2 s3

x=10 x=10 x=10

135
Copy Constructors Shallow Copy
copies the address
of s.data to t .data
#include<string.h>
void main()
class String { String s = "hello";
{ char* data; String t = s; // same as String t(s);
public: s.display( );
String(const char* s = "") t.display( ); hello
{ data = new char[20]; hello
t.assign(“world”); hello
strcpy(data,s); hello
s.display( ); world
world
} t.display( ); world
world
~String( ) }
{ delete [ ] data; }
data
void assign(char *str) hello\0
{ strcpy(data,str); }
data
void display()
{ cout << data; } data
}; world\0
data

136
Copy Constructors
String(const String& s)
{
data = new char[strlen(s.data)+1];
strcpy(data, s.data); Deep Copy copies the
} value of the object s to t

data hello\0

Deep copy

data
hello\0

137
Constructor with initialization list
 Initialization of data members can also be done using initialization
list.
 Syntax:
class_name(arg_list) : InitializationSection
{ }
Example: class A
{
int a;
void main( )
int b; {
public: A object1(10);
A(int x):a(x),b(2*x){ }
void print( ){ cout<<a<<b; }
object1.print()
}; }

10
10 20
20

 For references and const data members constructor with


initialization list is a must (no default constructor is provided).

138
Destructor

139
Destructors
 When an object goes out of scope then it is automatically
destroyed.

 It performs clean up of the object ( in the case of allocating


memory inside the object using new )

 Destructors have the same name as class preceded with tilde (~)

 They have no arguments and thus cannot be overloaded

Syntax:

~ classname() { }

Example:
~sum( ) { }

140
Allocating memory using new
Point *p = new Point(5, 5);

 new can be thought of a function with slightly strange


syntax
 new allocates space to hold the object.
 new calls the object’s constructor.
 new returns a pointer to that object.

141
Deallocating memory using delete
// allocate memory
Point *p = new Point(5, 5);

...
// free the memory
delete p;

For every call to new, there must be


exactly one call to delete.

142
Using new with arrays
int x = 10;
int* nums1 = new int[10]; // ok
int* nums2 = new int[x]; // ok

 Initializes an array of 10 integers on the heap.


 C++ equivalent of
int* nums = (int*)malloc(x * sizeof(int));

143
Using new with multidimensional
arrays
int x = 3, y = 4;
int* nums3 = new int[x][4][5];// ok
int* nums4 = new int[x][y][5];// BAD!

 Initializes a multidimensional array


 Only the first dimension can be a variable. The rest must
be constants.
 Use single dimension arrays to fake multidimensional
ones

144
Using delete on arrays
// allocate memory
int* nums1 = new int[10];
int* nums3 = new int[x][4][5];

...
// free the memory
delete[ ] nums1;
delete[ ] nums3;

 Have to use delete[].

145
Friends

146
Friends

 A friend of a class is a function that is not a member of


the class but is permitted to use the private and
protected member names from the class.

 The name of the friend is not in the scope of the class

 It is not called with the member access operator

 It uses the friend keyword

147
Difference between friends and
member function
class X {
int a;
friend void friend_set(X*,int);
public:
void member_set(int);
};
void f()
void friend_set(X* p,int i) {p- {
>a=i;} X obj;
void X::member_set(int i) friend_set(&obj,10);
{a=i;} obj.member_set(10);
}

148
Friend Class

 Entire class can be declared as friend for


another class.

 When a class is declared as friend, it means


the members of the friend class have access
to all the public / private / protected members
of the class in which the declaration was
made.

149
Friend class example
#include <iostream.h> void print(void)
class two; { cout<<"a="<<a<<"b="<<b; }
class one void assign(one x)
{ int a1,b1; { a=x.a1;
public: b=x.b1;
assign(void) }
{ a1=5, b1=10; } };
friend class two;
//friend void two::assign(one); void main(void)
};
{ one o1;
class two
{ two t1;
int a,b; o1.assign();
public: t1.let(4,2);
void let(int x, int y) t1.print();
t1.assign(o1); aa==44 b=
{ a=x; b=y; } b=22
t1.print(); a=
a=55 b=10
b=10
}

150
Inheritance

151
Inheritance – is a relationship
 Inheritance is a process of one class acquiring the features of another class.
 It is a way of creating new class(derived class) from the existing class(base
class) providing the concept of reusability.

A Surgeon “is a” Doctor. A Doctor need not be a surgeon


Account
Account Doctor
Doctor
acct_no
acct_no Name
Name
name
name Qualification
Qualification
balance
balance Operate
Operate
withdraw()
withdraw()
deposit(
deposit() )

Savings
SavingsAcc
Acc Current
CurrentAcc
Acc Dentist
Dentist Cardiologist
Cardiologist
interest
interest overdraft
overdraft Tooth
ToothSpecialist
Specialist Heart
HeartSpecialist
Specialist

152
Inheritance
 By using the concepts of inheritance, it is possible to create a
new class from an existing one and add new features to it.

 The class being refined is called the superclass or base class


and each refined version is called a subclass or derived class.

 Semantically, inheritance denotes an “is-a” relationship between


a class and one or more refined version of it.

 Attributes and operations common to a group of subclasses are


attached to the superclass and shared by each subclass
providing the mechanism for class level Reusability .

153
Inheritance
Person
Person
Name
Name
Sex
Sex
Age
Age

Student
Student Teaching
TeachingStaff
Staff
Reg.No.
Reg.No. Edn.Qual.
Edn.Qual.
Course
Course Designation
Designation
Marks
Marks Specialization
Specialization

“Person” is a generalization of “Student”.


“Student” is a specialization of “Person”.
154
Defining Derived Class
 The general form of deriving a subclass from a base class is as follows

Class derived-class-name : visibility-mode base-class-name


{
……………… //
……………….// members of the derived class
};

 The visibility-mode is optional.


 It may be either private or public or protected, by default it is private.
 This visibility mode specifies how the features of base class are visible to the
derived class.

155
Access control
Access Specifier and their scope
Base Class Access Derived Class Access Modes
Mode Private Public derivation Protected derivation
derivation
Public Private Public Protected
Private Not inherited Not inherited Not inherited
Protected private Protected Protected

Access control to class members


Access Directly to
Function Type Private Public Protected

Class Member Yes Yes Yes


Derived Class Member No Yes Yes
Friend Yes Yes Yes
Friend Class Member Yes Yes Yes 156
Access Specifiers with Inheritance
class Y : public X
{ void mderived( );
};
class X Y::mderived( )
{ int priv; { priv =1; //Error priv is private and
protected: //cannot be inherited
int prot; prot =2; // Ok
public: publ=3; // Ok
int publ; }
void m( );
}; void global_fun(Y *p)
void X::m( ) {
{ priv =1; //Ok p->priv = 1; //Error : priv is private of X
prot =1; //Ok p->prot = 2; //Error : prot is protected and
publ =1; //Ok //the function global_fun( )
} //is not a friend or a member of X or Y
p->publ =3; // Ok
}

157
Public, Protected and Private
derivation
Class A Class B Class B: Public A

private : private : private :


int a1; int b1; int b1;

protected : protected : protected:


int a2; int b2; int a2;
int b2

public : public : public:


int a3; int b3; int b3;int a3;

Public Derivation

158
Public derivation - example
class A
{ void main( )
private : int a; {
protected: int b; B b1;
public : void get_a( ) { cin>>a;} b1.get_a( );
void get_b( ) { cin>>b;} b1.get_b( );
b1.get_c( );
void print_a( ) { cout<<a;}
b1.get_d( );
void print_b( ) {cout<<b;}
b1.print_all( );
}; }
class B : public A
{
private : int c;
protected: int d;
public : void get_c( ) { cin>>c;}
void get_d( ) {cin >>d;}
void get_all( ) { get_a( ); cin>>b>>c>>d;}
void print_cd( ){ cout<<c<<d;}
void print_all( ) { print_a( ); cout<<b<<c<<d; }
};

159
Protected derivation - example
• The inherited public and protected members of a base class become
protected members of the derived class

Class A Class B Class B : Protected A

private : private : private :


int a1; int b1; int b1;

protected:
protected : protected :
int a2;
int a2; int b2;
int b2,a3;

public : public : public:


int a3; int b3; int b3;

Protected Derivation 160


Protected derivation - example
class A
void main( )
{
{
private: int a;
B b1;
protected: int b;
public : void get_a( ) { cin>>a;}
b1.get_a( ); //ERROR
void get_b( ) { cin>>b;}
b1.get_b( ); //ERROR
void print_a( ) { cout<<a;}
b1.get_ab( );
void print_b( ) {cout<<b;} b1.get_c( );
}; b1.get_d( );
b1.print_all( );
}
class B : protected A
{ private : int c;
protected: int d;
public : void get_c( ) { cin>>c;}
void get_d( ) {cin >>d;}
void get_ab( ) { get_a( ); get_b( );}
void print_cd( ){ cout<<c<<d;}
void print_all( ) { print_a( ); cout<<b<<c<<d;};
}

161
Private derivation - example
The inherited public and protected members of a private derivation
become private members of the derived class.

Class A Class B Class B : private A

private : private : private :


int a1; int b1; int b1;
int a2,a3;
protected : protected :
int a2; int b2; protected:
int b2;
public : public :
int a3; int b3; public:
int b3;

Private Derivation
162
Private derivation - example
class A
{
Class C : public B
private: int a; { public :
protected: int b; void get_all( )
public : void get_a( ) { cin>>a;} { get_a( ); //ERROR
void get_b( ) { cin>>b;} get_b( ); //ERROR
void print_a( ) { cout<<a;} get_ab( ); //Ok
void print_b( ) {cout<<b;} get_c( ); //Ok
}; get_d( ); //Ok }
void print_all( )
{ print_a( ); //ERROR
print_b( ); //ERROR
class B : private A print_cd( ); //Ok
{ print_abcd( ); //Ok } };
private : int c; void main( )
protected: int d; { C c1;
public : void get_c( ) { cin>>c;} c1.get_a( ); //ERROR
c1.get_b( ); //ERROR
void get_d( ) {cin >>d;} c1.get_c( ); // Ok
void get_ab( ) { get_a( ); get_b( );} c1.get_d( ); //Ok
void print_cd( ){ cout<<c<<d;} c1.getall( ); //Ok
void print_abcd( ) { print_a( ); cout<<b<<c<<d; } c1.print_all( ); //Ok
}; }

163
Types of Inheritance

Inheritance are of the following types

• Simple or Single Inheritance


• Multi level or Varied Inheritance
• Multiple Inheritance
• Hierarchical Inheritance
• Hybrid Inheritance
• Virtual Inheritance

164
Simple or Single Inheritance
 This is a process in which a sub class is derived from only one superclass.

 a Class Student is derived from a Class Person

class Person
Person superclass(base class)
{ ….. };

class Student : public Person

{
Student subclass(derived class) …………
};

visibility mode

165
Multilevel or Varied Inheritance
 The method of deriving a class from another derived class is known as
Multiple or Varied Inheritance.

 A derived class CS-Student is derived from another derived class Student.

Person
Class Person
{ ……};
Student Class Student : public Person
{ ……};
Class CS -Student : public Student
CS -Student { …….};

166
Multiple Inheritance
 A class is inheriting features from more than one super class.

 Class Part-time Student is derived from two base classes, Employee


and Student .

Employee Student Class Employee


{……..};
Class Student
{……..};
Class Part-time Student : public Employee,
public Student
Part-time Student
{…….};

167
Hierarchical Inheritance
 Many sub classes are derived from a single base class

 The two derived classes namely Student and Employee are derived
from a base class Person.

Class Person
Person {……};
Class Student : public Person
{……};
Class Employee : public Person
Student Employee
{……};

168
Hybrid Inheritance
 In this type, more than one type of inheritance are used to derive a new sub
class.

 Multiple and multilevel type of inheritances are used to derive a class PG-
Student.

Person class Person


{ ……};
class Student : public Person
{ ……};
class Gate Score
Student Gate Score {…….};
class PG - Student : public Student,
public Gate Score
{………};

PG - Student

169
Virtual Inheritance
 A sub class is derived from two super classes which in-turn have been
derived from another class.

 The class Part-Time Student is derived from two super classes namely,
Student and Employee.

 These classes in-turn derived from a common super class Person.

 The class Part-time Student inherits, the features of Person Class via two
separate paths.

170
Virtual Inheritance
Person

Student Employee

Class Person
Part-time Student {……};
Class Student : public Person
{……};
Class Employee : public Person
{……};
Class Part-time Student : public Student,
public Employee
{…….};

171
Derived Class Constructors

 A base class constructor is invoked(if any) , when a derived class object is


created.

 If base class constructor contains default constructor, then the derived class
constructor need not send arguments to base class constructors explicitly.

 If a derived class has constructor, but base class has no constructor, then the
appropriate derived class constructor executed automatically whenever a
derived class object is created.

172
Derived Class Constructors
class B
{
int x;
public :
B( ) { cout<<”B::B( ) Ctor…”<<endl;}
};
class D : public B
{
int y; B::B( ) Ctor …
public : D::D( ) Ctor …
D( ) { cout<<”D::D() Ctor …”<<endl;}
};
void main( )
{
D d;
}

173
Derived Class Constructors
class B
{
int a;
public :
B( ) { a = 0; cout<<”B::B( ) Ctor…”<<endl;}
B(int x) { a =x; cout<<”B::B(int) Ctor…”<<endl;}
};
class D : public B
{ int b; B::B( ) Ctor…
public : D::D( ) Ctor…
D( ) { b =0; cout<<”D::D( ) Ctor…”<<endl;} B::B( ) Ctor…
D(int x) { b =x; cout<<”D::D(int) Ctor…”<<endl;} D::D(int) Ctor…
D(int x, int y) : B(y) B::B(int) Ctor…
{ b =x; cout<<”D::D(int, int) Ctor…”<<endl;} D::D(int, int) Ctor…
};
void main( )
{
D d;
D d(10);
D d(10, 20);
}

174
Derived Class Destructors
Derived class destructors are called before base class destructors.

class B
{
int x;
public :
B( ) { cout<<”B Constructor Invoked…”<<endl;}
~B( ) { cout<<”B Destructor Invoked …”<<endl;}
}; B Constructor Invoked…
class D : public B D Constructor Invoked…
{ D Destructor Invoked…
int y; B Destructor Invoked …
public :
D( ) { cout<<”D Constructor Invoked …”<<endl;}
~ D( ) { cout<<”D Destructor Invoked…”<<endl;}
};
void main( )
{ D d; }

175
Overriding Member Functions
 When the same function exists in both the base class and the derived class,
the function in the derived class is executed

class A void main( )


{ {
protected : int a;
public : B b1;
void getdata( ) { cin>>a;} b1.getdata( ); // B::getdata( )
void putdata( ) { cout << a;} //is invoked
}; b1.putdata( ); // B::putdata( )
class B : public A //is invoked
{ b1.A::getdata( ); // A::getdata( )
protected: int b; // is invoked
public : void getdata( ) b1.A::putdata( ); // A::putdata( )
{ cin>>a>>b;} //is invoked
void putdata( ) { cout<<a<<b;} }
};

176
Composition
• Classes having objects of other classes as their data members -
composite classes
class y
{
class x int i;
{ int i; public:
public: X x;
x() Y()
{i=0;} { i=0;}
void set(int j) void f(intj)
{ i=j;} { i=j;}
int read() const int g() const
{ return i;} { return i;}
}; };
int main()
{ Y y;
y.f(5);
y.x.set(10);
}

177
Inheritance : Summary
 A subclass may be derived from a class and inherit its methods and
members.
 Semantically, inheritance denotes an “is-a” relationship between a class
and one or more refined version of it.

 Different types are


 Single inheritance
 Multiple inheritance
 Multilevel inheritance

 Base class constructors are also executed whenever derived class


objects created.

 Derived class can override a member function of a base class.

178
Virtual Functions and
Polymorphism

179
Polymorphism
• Greek word meaning - many or multiple forms.

• In programming languages, polymorphism means that some code or


operations or objects behave differently in different contexts

• It provides a single interface to entities of different types.

Types of Polymorphism
Polymorphism

Static Polymorphism Dynamic Polymorphism

Function Overloading Operator Overloading Virtual Function

180
Polymorphism

Binding

 Determining a location in memory by the compiler


 Connecting a function call to a function body
 The location may represent the following
 Variable names bound to their storage memory address (offset)
 Function names bound to their starting memory address (offset)

Two kinds of binding

• Compile-Time Binding
• Run-Time Binding

181
Static Polymorphism

 Compile-time binding or early binding is called as static


polymorphism.

 Compile-Time Binding means

 Compiler has enough information to determine an address


(offset)

 Named variables / function calls have their addresses fixed


during compilation

182
Virtual Functions
 Virtual function is a member function that is declared in the base class (using
keyword virtual) and is redefined in the derived class.

 Dynamic binding means that the actual function invoked at run time depends on
the address stored in address.

 Virtual functions are overriding functions to achieve dynamic binding.

class One void main()


{ public: {
virtual void whoami() One one, *ptr ;
{cout<<”One”<<endl; } Two two;
}; ptr=&one;
class Two : public One ptr->whoami( );
{ public: ptr=&two;
void whoami() ptr->whoami( ); One
{cout<<”Two”<<endl; } } Two
};
183
Virtual Function
Implementation
VTABLE (Virtual Table):

 The compiler creates a VTABLE for every class and its


derived class having virtual functions, which contains
addresses of virtual functions.

 If no function is redefined in the derived class that is defined


as virtual in the base class, the compiler takes the address of
base class function.

VPTR ( Virtual Pointer):

 When objects of base or derived classes are created, a void


pointer is inserted in the VTable called VPTR.
184
Virtual Function Implementation
class Base
{ void main()
public : {
Base b1;
Base() { }
Derived d1;
virtual void f1() { cout<<”base::f1( )” << endl; }
Base *p=&b1;
virtual void f2( ) { cout << Base:: f2()”<<endl; } p->f1(); // base::f1
void f3() { cout<<”Base :: f3()”<<endl; } p->f2(); //base::f2
}; p->f3(); //base::f3
class Derived :public Base Base *q =&d1;
{ q->f1(); //Derived::f1
public: q->f2(); //Base::f2
q->f3(); //Base::f3
Derived() { }
}
void f1() { cout<<”Derived ::f1()”<<endl; }
};

185
Virtual Function Implementation
contd…
Pointers Objects Vtables

Object Base::f1()
b1
P Vptr Base::f2()

Object
d1 Derived::f1()
q Vptr
Base::f2()

186
Abstract Class & Pure Virtual
Functions
Abstract Class

• A class that serves only as a base class from which other classes can
be derived

• If a base class declares contains pure virtual functions , no instance of


the class can be created.

Pure Virtual Functions

 In practical applications, the member functions of base classes is rarely


used for doing any operation (null body).

Syntax:
Virtual void display( )=0;

187
Abstract Classes
 An abstract class represents an abstract concept in C++ (such as
Shape class)

Shape 1. Defines the interfaces that all of


the concrete classes (subclasses)
share

Circle Polygon 2. Does not define state and


implementation unless it is
common to all concrete classes

Rectangle 3. Cannot be instantiated

188
Pure Virtual Function

class Base class Derv2 : public Base


{ public: { public:
void show()
virtual void show()=0; { cout<<”In Derv2”; }
};
// Pure Virtual function void main()
}; {
Base *List[2];
class Derv1 : public Base Derv1 dv1;
{ Derv2 dv2;
List[0]=&dv1;
public: List[1]=&dv2;
List[0]->show();
void show()
List[1]->show();
{ cout<<” In Derv 1”; } }
};

189
Virtual Destructor
 When a derived object pointed to by the base class pointer is deleted, dtor of
the derived class as well as the dtors of all its base classes are invoked.

#include<string.h> class son: public Father


class Father {
{ char* name; char* name;
public:
public:
Father(const char* s = "")
{ name = new char[20]; son(const char* s = "")
strcpy(name,s); } { name = new char[20];
virtual ~Father( ) strcpy(name,s);
{ delete [ ] name; }
}
virtual void display()
~son( )
{ cout << name; { delete [ ] name;
} }
}; void display()
{ cout << name;
}
}; Contd.. 190
Virtual Destructor

void main()
{
Father *bp,s = “ABC"; // same as Father s(“ABC");
bp=&s;
cout <<”s=”<<bp->display( );
delete bp;
son s1=“XYZ”;
bp=&s1;
cout<<”s1=”<<bp->display();
delete bp; s = ABC
} S1=XYZ

191
Why not virtual
constructor??????

192
Rules for Virtual Functions

 They should not be static.

 They can be friend function of another class.

 Constructors cannot be declared as virtual, but destructors can


be declared as virtual.

 The virtual function must be defined in public section of the class.

193
Polymorphism - Summary
 Function overloading and operator overloading are used to achieve
static polymorphism.

 Virtual functions are used to achieve dynamic polymorphism.

 Pointers to objects of base classes are type compatible with pointers to


objects of derived classes. Reverse is not possible.

 Virtual functions can be invoked using pointer or reference.

 Abstract base class is the one having pure virtual function.

194
Overloading Vs Overriding

 Overloading
 Same name and scope of the class
 Different signature
 Doesn't require virtual keyword
 Overriding
 Same name and Signature
 Different class scope
 Require virtual keyword

195
Operator Overloading

196
Operator overloading
 Enabling C++’s operators to work with class objects
 Using traditional operators with user-defined objects
 A way of achieving static polymorphism is Operator overloading

Example:

 Operator << is both the stream-insertion operator and the bitwise left-
shift operator
 + and -, perform arithmetic on multiple types

4+5 - integer addition


3.14 + 2.0 - floating point addition
“sita” + "ram" - string concatenation

 Compiler generates the appropriate code based on the manner in


which the operator is used
197
Operator overloading

 Overloading an operator

 Write function definition as normal


 Function name is keyword operator followed by the
symbol for the operator being overloaded
 operator+ used to overload the addition operator (+)

 Two ways of overloading the operators using


 Member function
 Friend function

198
Operator Overloading
Syntax (using member function):

Keyword Operator to be overloaded

ReturnType classname :: Operator OperatorSymbol (argument list)


{
\\ Function body
}

 Number of arguments in a member function for


 Unary operator – 0
 Binary operator – 1

199
Operator Overloading
Syntax (using friend function):
Keyword Operator to be overloaded

ReturnType operator OperatorSymbol (argument list)


{
\\ Function body
}

Number of arguments in a friend function for


 Unary operator – 1
 Binary operator – 2

200
Binary Operator Overloading
 To declare a binary operator function as a member function
 ret-type operatorop( arg )
class time void main(void)
{ {
int hrs, mins; time t1(10,20), t2(11,30);
public: t1.show();
void set(int h,int m) t2.show();
{ hrs=h;mins=m;} // t1.sum(t2);
void show() t1=t1+ t2;
{ cout<<hrs<<“:”<<mins; } t1.show();
void sum(time t) t2.show();
{ hrs+=t.hrs; mins+=t.mins; } }
time operator + (time t) Hrs 10: 20 mins
{ time temp; Hrs 11: 30 mins
temp.hrs=hrs+t.hrs; Hrs 21: 50 mins
temp.mins=mins+t.mins; Hrs 11: 30 mins
return temp;}
};
201
Binary Operator Overloading

 To declare a binary operator function as a friend function


 ret-type operatorop( arg1, arg2 )
class time void main(void)
{ {
int hrs, mins; time t1(10,20), t2(11,30);
public: t1.show();
void set(int h,int m) t2.show();
{ hrs=h;mins=m;} t1=t1+ t2;
void show() t1.show();
{ cout<<hrs<<“:”<<mins; } t2.show();
friend time operator + (time,time); }
}; Hrs 10: 20 mins
time operator + (time t1,time t2) Hrs 11: 30 mins
{ time temp; Hrs 21: 50 mins
temp.hrs=t1.hrs+t2.hrs; Hrs 11: 30 mins
temp.mins=t1mins+t2.mins;
return temp; }

202
Binary Operator Overloading

Point Point::operator+ (Point P)


{
class Point { Point temp;
public: temp.x = x + P.x;
int x,y; temp.y = y + P.y;
Point () { }; return (temp);
Point (int,int); }
Point operator + (Point); int main ()
}; {
Point::Point (int a, int b) { Point a (3,1);
x = a; Point b (1,2);
y = b; Point c;
} c = a + b; // c=a.operator+(b);
cout << c.x << "," << c.y;
return 0;
}
2,3

203
Operator Overloading
Operators that can be overloaded
+ - * / % ^ & |
~ ! = < > += -= *=
/= %= ^= &= |= << >> >>=
<<= == != <= >= && || ++
-- ->* , -> [] () new delete
new[] delete[]

Operators that cannot be overloaded


. .* :: ?: sizeof

204
Operator Overloading
Operators that can be overloaded using member and friend functions:

Using member function Using friend function


Operators = <<
() >>
[]
->

205
Unary Operators Overloading
 To declare a unary operator function as a
member function
 return-type operatorop()
class Point
void main()
{  int x, y;
{
public:
Point p, p1,p2;
  Point() {x = y = 0; }
p1= p++;
Point& operator++()
p2= --p;

}
x++;
y++;
return *this;
}
Point& operator--()
{ x--;   y--;   return *this;}
};

206
Unary Operators Overloading
 To declare a unary operator function as a friend function
 ret-type operatorop(arg)
class Point
{  int x, y;
public:
   Point() {x = y = 0; }
Point& operator++()
{ x++;
y++; void main()
return *this;} {
friend point operator –(point); Point p, p1,p2;
}; p1= p++;
Point operator--(point &p) p2= --p;
{ p.x--; }
   p.y--;
   return p;
}

207
Unary Operators Overloading
• There is no distinction between the prefix and postfix overloaded operator
functions.
• The new syntax for postfix operator overloaded function is
ret-type operatorop(int) // member function
ret-type operatorop(arg,int) // friend function

class Point
void main()
{  int x, y;
{
public:
Point p, p1,p2;
   Point() {x = y = 0; }
p1= p++;
p2= --p;
Point& operator++(int)
}
{  x++;  y++;  return *this; }

Point& operator--()
{ x--;   y--;   return *this;}
};

208
Unary Operators Overloading
• The same operators can be defined using the following
(friend) function declarators:

friend Point& operator++( Point& ) // Prefix increment


friend Point& operator++( Point&, int ) // Postfix increment
friend Point& operator--( Point& ) // Prefix decrement
friend Point& operator--( Point&, int ) // Postfix decrement

209
Friend operator Functions Add
Flexibility
 Overloading an operator by using a friend or a member
function makes, no functional difference.

 In exceptional situation in which overloading by using a friend


increases the flexibility of an overloaded operator.

 Example:
 Object + 100
 100 + object
 In this case, it is integer that appears on the left.

210
Friend operator Functions Add
Flexibility
class Point Point operator+ (int i, Point P)
{ { Point temp;
public: temp.x = i + P.x;
int x,y; temp.y = i + P.y;
Point () {}; return (temp); }
Point (int,int);
friend Point operator +(int, Point); void main ()
friend Point operator +(Point, int); { Point a (3,1);
}; Point b (1,2);
Point::Point (int a, int b) Point c;
{ x = a; y = b;} c = a + 5;
Point operator+ (Point P, int i) cout << c.x << "," << c.y;
{ Point temp; c=10+a;
temp.x = P.x + i; cout << c.x << "," << c.y;
temp.y = P.y + i; }
return (temp); }

211
Operator Functions
as Class Members vs. as friend Functions
 Member vs non-member
 Operator functions can be member or non-member functions.
 When overloading ( ), [ ], -> or any of the assignment operators,
a member function must be used.
 Operator functions as member functions
 Leftmost operand must be an object (or reference to an object) of
the class
 If left operand of a different type, operator function must be a

non-member function
 Operator functions as non-member functions
 Must be friends if needs to access private or protected members
 Enable the operator to be commutative

212
Assignment operator overloading
 Assignment operator (=) is, strictly speaking, a binary operator. Its
declaration is identical to any other binary operator.

Exceptions:

 It must be a non-static member function. No operator = can be


declared as a non-member function.

 It is not inherited by derived classes.

 A default operator= function can be generated by the compiler for


class types if none exists (bitwise shallow copy)

 User defined operator= function performs member wise deep copy.

213
Assignment operator overloading
class String void main() Default
{ { assignment
char* data; String s = "hello";
public: String t;
String(){ data=NULL; } t=s;
hello
hello
s.display( ); hello
String(const char* s = "") hello
t.display( ); world
{ data = new char[20]; world
t.assign(“world”); world
world
strcpy(data,s); s.display( );
} t.display( );
~String( ) }
{ delete [ ] data;
data
}
hello\0
void assign(char *str)
{strcpy(data,str); data
}
void display() data
{ cout << data; world\0
} data
}; 214
Assignment operator overloading
void operator=(const String& s)
Overloaded operator function
{
data = new char[strlen(s.data)+1];
strcpy(data, s.data);
}

data hello\0

Deep copy

data
hello\0

215
Overloading IO
Overloaded << and >> operators
Stream operators
 Overloaded to perform input/output for user-defined types
 Left operand of types ostream & and istream &
 Must be a non-member function because left operand is not an object of the class
 Must be a friend function to access private data member

Example: cin>>account;
cout<<account;
Syntax:

Output stream Keyword Ostream object:


cout
Keyword Reference types Ostream operator User defined object

friend ostream & operator << ( ostream &out, arg)


{ //display attributes
return out
}
216
Overloading IO Stream operators
class Point
{
public:
int x,y;
Point () {};
Point (int,int);
friend ostream& operator<<(ostream&, const point&);
friend istream& operator>>(istream&, const point&);
}; void main()
Point::Point (int a, int b) {
{ x = a; y = b;} Point p1(2,3), p2(0,0);
ostream& operator<<(ostream& os, const Point& a) cin>>p2;
{ os << a.x; cout<<p1;
os << a.y; cout<<p2;
return os; }
}
istream& operator>>(istream& is, Point& a)
{ is >> a.x;
is >> a.y;
return is;
}
217
Type Conversion
 Compiler supports data conversion of only built-in data types.

 In case of user defined data type conversion, the data conversion interface
function must be explicitly specified by the user.

 A single argument constructor or an operator function could be used for conversion


of objects of different classes.

Conversion
type Source class Destination class

Basic class Not applicable Constructor

Class basic Casting Operator Not Applicable

Class class Casting operator Constructor

218
Basic to User defined data type
 To convert basic to user-defined data type, single argument constructor conversion
routine should be written in the destination object class.
class Meter
{
float length;
public:
Meter (float len)
{ length=len; }
};
main()
{
float length1=15.56;
meter1=length1; // Converts basic data item length1 of float type
to the object meter1 by // invoking the one-argument
constructor.
}

This constructor is invoked while creating objects of class Meter using a single argument
of type float.
It converts the input argument represented in centimeters to meters and assigns the
resultant value to length data member.
219
User defined data type to Basic Conversion
 To convert user-defined data type to basic, operator
function should be written in the source object class.

class Meter main()


{ {
float length; float length2;
public: Meter meter2(100);
length2=(float) meter2;
Meter (float len)
// length2 = float(meter2);
{ length=len; } }
operator float()
{ float len_cms;
len_cms = length * 100.0; // meter to cm.
return (len_cms);
}
};

220
Class to Class Conversion
Conversion routine in source class: Operator function

 To convert user-defined data type to another user-defined data type,


operator function should be written in the source object class.

class Meter main()


{ float length;
{
public:
Meter m(5);
Meter (float len)
{ length=len; }
CentiMeter cm;
operator CentiMeter() cm=m;
{ return CentiMeter(len*100.0); } }
};
class CentiMeter
{ float Clength;
public:
CentiMeter (float len)
{ Clength=len; }
};

221
Class to Class Conversion
Conversion routine in destination class: constructor function

 To convert user-defined data type to another user-defined data type,


constructor function should be written in the destination object class.

class Meter
{ float length; main()
public: {
Meter (float len) Meter m(5);
{ length=len; } CentiMeter cm;
float getlength(){ return length;} cm=m;
}; }
class CentiMeter
{ float Clength;
public:
CentiMeter (float len)
{ Clength=len; }
CentiMeter(Meter m)
{ Clength= m.getlength()*100.0);}
};

222
Restrictions on Operator

Overloading
Overloading restrictions
 Precedence and associativity of an operator cannot be changed
 Arity (number of operands) cannot be changed
 Unary operators remain unary, and binary operators remain binary
 Operators &, *, + and - each have unary and binary versions
 Unary and binary versions can be overloaded separately

 No new operators can be created


 Use only existing operators

 No overloading operators for built-in types (cannot redefine the


meaning of operators)
 Cannot change how two integers are added
 Produces a syntax error

223
Implementing Operator Overloading

 Two ways:
 Implemented as member functions
 Implemented as non-member or Friend functions
 the operator function may need to be declared as a friend if it

requires access to protected or private data

 Expression obj1@obj2 translates into a function call


 obj1.operator@(obj2), if this function is defined within class obj1
 operator@(obj1,obj2), if this function is defined outside the class
obj1

224
Implementing Operator Overloading

1. Defined as a member function


class Complex {
...
public:
... c = a+b;
Complex operator +(const Complex &op)
{
double real = _real + op._real,
imag = _imag + op._imag; c = a.operator+ (b);
return(Complex(real, imag));
}
...
};

225
Implementing Operator Overloading

2. Defined as a non-member function


class Complex {
... c = a+b;
public:
...
double real() { return _real; } c = operator+ (a, b);
//need access functions
double imag() { return _imag; }
...
}; Complex operator +(Complex &op1, Complex &op2)
{
double real = op1.real() + op2.real(),
imag = op1.imag() + op2.imag();
return(Complex(real, imag));
} 226
Implementing Operator Overloading

3. Defined as a friend function


class Complex {
... c = a+b;
public:
...
friend Complex operator +( c = operator+ (a, b);
const Complex &,
const Complex &
);
... Complex operator +(Complex &op1, Complex &op2)
}; {
double real = op1._real + op2._real,
imag = op1._imag + op2._imag;
return(Complex(real, imag));
} 227
Overloading stream-insertion and
stream-extraction operators
 In fact, cout<< or cin>> are operator overloading built in C++ standard lib of
iostream.h, using operator "<<" and ">>"
 cout and cin are the objects of ostream and istream classes, respectively
 We can add a friend function which overloads the operator <<

friend ostream& operator<< (ostream &ous, const Date &d);

ostream& operator<<(ostream &os, const Date &d)


{
os<<d.month<<“/”<<d.day<<“/”<<d.year;
return os;
cout ---- object of ostream
}

cout<< d1; //overloaded operator
228
Overloading stream-insertion and
stream-extraction operators
 We can also add a friend function which overloads the operator >>

friend istream& operator>> (istream &in, Date &d);

istream& operator>> (istream &in, Date &d)


{
char mmddyy[9];
in >> mmddyy; cin ---- object of istream
// check if valid data entered
if (d.set(mmddyy)) return in;
cout<< "Invalid date format: "<<d<<endl;
exit(-1);
}
cin >> d1;

229
Class Template

230
Class Template
• A C++ language construct that allows the compiler
to generate multiple versions of a class by allowing
parameterized data types.

Class Template

Template < TemplateParamList >


ClassDefinition

TemplateParamDeclaration: placeholder

class typeIdentifier
typename variableIdentifier
231
Example of a Class Template
template<class ItemType>
class GList
{ Template
public: parameter
bool IsEmpty() const;
bool IsFull() const;
int Length() const;
void Insert( /* in */ ItemType item );
void Delete( /* in */ ItemType item );
bool IsPresent( /* in */ ItemType item ) const;
void SelSort();
void Print() const;
GList(); // Constructor
private:
int length;
ItemType data[MAX_LENGTH];
};
232
Instantiating a Class Template
• Class template arguments must be explicit.
• The compiler generates distinct class types
called template classes or generated classes.
• When instantiating a template, a compiler
substitutes the template argument for the
template parameter throughout the class
template.

233
Instantiating a Class Template
To create lists of different data types
// Client code
template argument
 
GList<int> list1;
GList<float> list2;
GList<string> list3;
 
list1.Insert(356); Compiler generates 3
list2.Insert(84.375); distinct class types
list3.Insert("Muffler bolt");
GList_int list1;
GList_float list2;
GList_string list3;

234
Substitution Example
class GList_int
{
public: int

void Insert( /* in */ ItemType item );


int
void Delete( /* in */ ItemType item );

bool IsPresent( /* in */ ItemType item ) const;

private: int
int length;
ItemType data[MAX_LENGTH];
};
int

235
Function Definitions for Members of a
Template Class
template<class ItemType>
void GList<ItemType>::Insert( /* in */ ItemType item )
{
data[length] = item;
length++;
}

//after substitution of float


void GList<float>::Insert( /* in */ float item )
{
data[length] = item;
length++;
} 236
Another Template Example:
passing two parameters

template <class T, int size>


class Stack {...
T buf[size]; non-type parameter
};
Stack<int,128> mystack;

237
Vectors

238
Vector

 A sequence that supports random access to


elements
 Elements can be inserted and removed at the
beginning, the end and the middle
 Constant time random access
 Commonly used operations
 begin(), end(), size(), [], push_back(…), pop_back(),
insert(…), empty()

239
Example of vectors

// Instantiate a vector
vector<int> V;

// Insert elements
V.push_back(2); // v[0] == 2
V.insert(V.begin(), 3); // V[0] == 3, V[1] == 2

// Random access
V[0] = 5; // V[0] == 5

// Test the size


int size = V.size(); // size == 2

240
Exception Handling

241
Exception
• An exception is a unusual, often unpredictable
event, detectable by software or hardware, that
requires special processing occurring at runtime
• In C++, a variable or class object that
represents an exceptional event.

242
Handling Exception
• If without handling,
• Program crashes

• Falls into unknown state

• An exception handler is a section of program code that


is designed to execute when a particular exception
occurs
• Resolve the exception

• Lead to known state, such as exiting the program

243
Standard Exceptions
 Exceptions Thrown by the Language
 new
 Exceptions Thrown by Standard Library
Routines
 Exceptions Thrown by user code, using
throw statement

244
The throw Statement
Throw: to signal the fact that an exception
has occurred; also called raise

ThrowStatement
throw Expression

245
The try-catch Statement
How one part of the program catches and processes
the exception that another part of the program throws.
TryCatchStatement
try
Block
catch (FormalParameter)
Block
catch (FormalParameter)
FormalParameter
DataType VariableName


246
Example of a try-catch Statement
 try
{
// Statements that process personnel data and may throw
// exceptions of type int, string, and SalaryError
}
catch ( int )
{
// Statements to handle an int exception
}
catch ( string s )
{
cout << s << endl; // Prints "Invalid customer age"
// More statements to handle an age error
}
catch ( SalaryError )
{
// Statements to handle a salary error
}
247
Execution of try-catch

A No
statement throws statements throw
an exception an exception

Control moves Exception


directly to exception
handler
Handler

Statements to deal with exception are executed

Statement
following entire try-catch
statement
248
Throwing an Exception to be
Caught by the Calling Code
void Func3()
{

try
{ Function void Func4()
call {
Func4();
Normal if ( error )
} return throw ErrType();
catch ( ErrType )
{ }
}
Return from
} thrown
exception
249
Practice: Dividing by ZERO

Apply what you know:


int Quotient(int numer, // The numerator
int denom ) // The denominator
{
if (denom != 0)
return numer / denom;
else
//What to do?? do sth. to avoid program
//crash
}

250
A Solution

int Quotient(int numer, // The numerator


int denom ) // The denominator
{
if (denom == 0)
throw DivByZero();
//throw exception of class DivByZero
return numer / denom;
}

251
A Solution

// quotient.cpp -- Quotient program while(cin)


  {
#include<iostream.h> try
{
#include <string.h> cout << "Their quotient: "
int Quotient( int, int ); << Quotient(numer,denom) <<endl;
class DivByZero {}; // Exception class }
catch ( DivByZero )//exception handler
int main()
{
{
cout<<“Denominator can't be 0"<< endl;
int numer; // Numerator }
int denom; // Denominator // read in numerator and denominator
}
//read in numerator return 0;
and denominator }

252
End

253

You might also like