Object Oriented Programming
Object Oriented Programming
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
6
Abstraction
Real World Abstraction Object-Oriented
Programming
Properties Data
Entity
Operations Functions
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]
Since the classes use the concept of data abstraction, they are
known as Abstract Data Types (ADT).
8
Characteristics of Object Oriented
Programming
Abstraction
Encapsulation
Inheritance
Polymorphism
9
Encapsulation
State
Class
Behavior
10
Encapsulation
Interface Implementation
11
Encapsulation
Bundling of data and functions together into a single unit (class).
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.
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
14
Characteristics of Object Oriented
Programming
Abstraction
Encapsulation
Inheritance
Polymorphism
15
Polymorphism
Polymorphic: from the Greek for “many forms”
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
20
Identity
21
What is an object?
OBJECT
set of methods
Operations
internal state
Data
22
Class & Object
Class:
Object:
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
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.
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
30
Why << ?
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
33
Streams for Input and Output
#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
#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
37
Declarations and
Definitions
38
Declarations
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
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
42
Scope
A declaration introduces a scope
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;
}
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).
45
lvalue and rvalue
46
lvalue (location value)
lvalue is an expression referring to an object or
function.
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
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
#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’;
}
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
#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
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
}
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’
69
Reference
int ii=0;
int &rr=ii;
rr++; // ii is incremented
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
Some Exceptions
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
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
75
References and Pointers
76
Reference to constant
77
Parameter passing
mechanisms
78
Parameter passing mechanisms
Call by value
Call by address
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.
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.
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;
}
85
Reference as return values
int& rmax(int &m,int &n)
{
if(m>=n)
return m;
else
return n;
}
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.
}
89
int &f()
.
.
.
int *x;
x=f();
90
Class in C++
91
Class declaration
class class-name
{
data-member declarations;
member-function declarations or definitions;
};
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
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
98
Declaring things const
// A const River
const River nile;
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
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;
}
107
Static Data Members
A static data member is initialized outside the class definition in
the same manner as a Non member variable.
void main()
{
float SavingsAccount::CurrentRate = 0.050;
}
108
Static Data Members
Only one initialization of a static data member can occur within a
program.
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.
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.
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);
}
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”
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)
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
}
121
Function Overloading
Example:
#include <iostream.h>
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.
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.
They are normally used to allocate memory for the data members and
initialize them.
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
127
Types of Constructors
Default Constructor
Parameterized Constructor
Overloaded Constructor
Dynamic Constructor
Copy Constructor
128
Default Constructor
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
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
Objects s1 s2 s3
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
138
Destructor
139
Destructors
When an object goes out of scope then it is automatically
destroyed.
Destructors have the same name as class preceded with tilde (~)
Syntax:
~ classname() { }
Example:
~sum( ) { }
140
Allocating memory using new
Point *p = new Point(5, 5);
141
Deallocating memory using delete
// allocate memory
Point *p = new Point(5, 5);
...
// free the memory
delete p;
142
Using new with arrays
int x = 10;
int* nums1 = new int[10]; // ok
int* nums2 = new int[x]; // ok
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!
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;
145
Friends
146
Friends
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
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.
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.
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
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
157
Public, Protected and Private
derivation
Class A Class B Class B: Public A
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
protected:
protected : protected :
int a2;
int a2; int b2;
int b2,a3;
161
Private derivation - example
The inherited public and protected members of a private derivation
become private members of the derived class.
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
164
Simple or Single Inheritance
This is a process in which a sub class is derived from only one superclass.
class Person
Person superclass(base class)
{ ….. };
{
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.
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.
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.
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.
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
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
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.
178
Virtual Functions and
Polymorphism
179
Polymorphism
• Greek word meaning - many or multiple forms.
Types of Polymorphism
Polymorphism
180
Polymorphism
Binding
• Compile-Time Binding
• Run-Time Binding
181
Static Polymorphism
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.
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
Syntax:
Virtual void display( )=0;
187
Abstract Classes
An abstract class represents an abstract concept in C++ (such as
Shape class)
188
Pure Virtual Function
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.
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
193
Polymorphism - Summary
Function overloading and operator overloading are used to achieve
static polymorphism.
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
Overloading an operator
198
Operator Overloading
Syntax (using member function):
199
Operator Overloading
Syntax (using friend function):
Keyword Operator to be overloaded
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
202
Binary Operator Overloading
203
Operator Overloading
Operators that can be overloaded
+ - * / % ^ & |
~ ! = < > += -= *=
/= %= ^= &= |= << >> >>=
<<= == != <= >= && || ++
-- ->* , -> [] () new delete
new[] delete[]
204
Operator Overloading
Operators that can be overloaded using member and friend functions:
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:
209
Friend operator Functions Add
Flexibility
Overloading an operator by using a friend or a member
function makes, no functional difference.
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:
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:
In case of user defined data type conversion, the data conversion interface
function must be explicitly specified by the user.
Conversion
type Source class Destination class
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.
220
Class to Class Conversion
Conversion routine in source class: Operator function
221
Class to Class Conversion
Conversion routine in destination class: constructor function
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
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
224
Implementing Operator Overloading
225
Implementing Operator Overloading
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
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
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++;
}
237
Vectors
238
Vector
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
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
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
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
250
A Solution
251
A Solution
252
End
253