Object Oriented Programming using C Plus Plus

suleman05cs32 10 views 186 slides Sep 21, 2024
Slide 1
Slide 1 of 186
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95
Slide 96
96
Slide 97
97
Slide 98
98
Slide 99
99
Slide 100
100
Slide 101
101
Slide 102
102
Slide 103
103
Slide 104
104
Slide 105
105
Slide 106
106
Slide 107
107
Slide 108
108
Slide 109
109
Slide 110
110
Slide 111
111
Slide 112
112
Slide 113
113
Slide 114
114
Slide 115
115
Slide 116
116
Slide 117
117
Slide 118
118
Slide 119
119
Slide 120
120
Slide 121
121
Slide 122
122
Slide 123
123
Slide 124
124
Slide 125
125
Slide 126
126
Slide 127
127
Slide 128
128
Slide 129
129
Slide 130
130
Slide 131
131
Slide 132
132
Slide 133
133
Slide 134
134
Slide 135
135
Slide 136
136
Slide 137
137
Slide 138
138
Slide 139
139
Slide 140
140
Slide 141
141
Slide 142
142
Slide 143
143
Slide 144
144
Slide 145
145
Slide 146
146
Slide 147
147
Slide 148
148
Slide 149
149
Slide 150
150
Slide 151
151
Slide 152
152
Slide 153
153
Slide 154
154
Slide 155
155
Slide 156
156
Slide 157
157
Slide 158
158
Slide 159
159
Slide 160
160
Slide 161
161
Slide 162
162
Slide 163
163
Slide 164
164
Slide 165
165
Slide 166
166
Slide 167
167
Slide 168
168
Slide 169
169
Slide 170
170
Slide 171
171
Slide 172
172
Slide 173
173
Slide 174
174
Slide 175
175
Slide 176
176
Slide 177
177
Slide 178
178
Slide 179
179
Slide 180
180
Slide 181
181
Slide 182
182
Slide 183
183
Slide 184
184
Slide 185
185
Slide 186
186

About This Presentation

Object Oriented Programming using C Plus Plus


Slide Content

lohan, SSE--> www. m | Website

bookspar.co!
| VTU NOTES

OBJECT ORIENTED
PROGRAMMING WITH
C++

B.R.MOHAN

CSE DEPT
SSE, MUKKA

Prof. B.R. Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

Text Book
1. Object oriented Programming with C++,
Sourav Sahay, Oxford Press, 2006
(chapters1-10)

Reference Books
Ak C++ Primer, Stanley Lipmann, Josee Lajoie,
Barbara E. Moo, 4" Edition, Addison Wesley,
2005

2. The Complete Reference C++,
Herbert Schildt, 4" Edition, TMH, 2005

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website

for students | VTU NOTES

1. Introduction to C++
2. Class and Object
Unit-2:
3. Class & Objects contd.
Unit-3:
4. Dynamic Memory Management
5. Constructors and Destructors

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES
Unit-4:

6. Inheritance
Unit-5:
7. Virtual Functions & Dynamic
Polymorphism

8. Stream Handling

Unit-6

9. Stream Handling contd 10. Operator
Overloading

for students | VTU NOTES
Unit-7:
11. Operator Overloading contd.

Unit-8:

12. Type Conversion, New style
casts, and RTTI

13. Templates FT,CT, STL

14. Exception Handling

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

Here we see how to program in C++ - a language that support
object oriented programming. Reference — Robert Lafore

Key concepts in OOPs - Objects and Classes

Oops came into existence due to the limitations
discovered in procedural languages.

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

Procedural Languages —

Pascal, C, Basic, Fortran are
examples of procedural languages.

lays emphasis on executing a set of
instructions.

-Get some input
-Add these numbers
-divide by 6

-display the results

for students | VTU NOTES
- A program in procedural language Is a list

of instructions.
For small programs, no other organizing
principle is needed.
- As program grows larger, it becomes difficult to

comprehend.

Hence Divide the large program into a
number of functions.

A Function has a clearly defined purpose
and a well defined interface.

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES

1. Dividing a function into a number of
functions can be extended to grouping a
number of functions into a larger entity
called Module.

2. Dividing a program into functions and

modules is one of the cornerstone of
Structured Programming( other features
include loops and other control structures).

3. | As program grow even larger, structured
programming signs of strain.

for students | VTU NOTES
Drawbacks/Disadvantages of Procedural languages.

1. Data is undervalued - given Il class status in
program organization of procedural languages.

2. Since many functions in a program can access
global data / global variables, global data can be
corrupted by that have no business to change it.
Global variables constitute data are declared
outside any function so that they are accessible to
all functions

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES

Since many functions access the same data,
the way data is arranged becomes critical.

+ Data arrangement cannot be changed
without modifying the functions that access
it. If u add new data items , we need to
modify all the functions that access the data
so that they can also access these new
items

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

Accessible by
any function

Accessible by Accessible by
Function A Function B

> =

FunctionA Function B

www.bookspar.com | Websit
for students | VTU NOTES

for students | VTU NOTES
Hence we need a way to restrict the access to the data , to hide

it from all but a few critical functions. This protects the data, simplifies the
maintainence and other benefits.

Object Oriented Approach

Idea of Object Oriented Language — data
and the functions that access the data are
combined into a single unit called OBJECT.

An objects functions are called Member
functions in C++.

MFs provide only way to access data.

for students | VTU NOTES
How to read a data item in an object ?

- Call the mf of the object and it will read the
data item and return the value to u.

- Data cant be accessed directly, it is hidden
within the object and safe from accidental
alterations.

- Data and functions are said to be
encapsulated in an object.

- Data Encapsulation & Data Hiding are the key
terms in OOPs

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

- OOPs simplify writing , debugging and
maintaining the program.

+ C++ prg typically contain a number of objects
interacting with each other by calling one
another’s member functions.

Prof. B.R.Mohan, www.bookspar.com | Website

for students | VTU NOTES

CSE Dept

Finance

Personnel Dept

Dept

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

There is a close match between programming sense &
objects in real world
Classes — Objects are instances / members of

a class.
Eg- All programming languages have built in

data types like int, char, float,etc.

Similarly u can have objects of same class as
shown

B.R.Mohan, SSI www.bookspar.com | Web:

for students | VTU NOTE:
plate like st re,
ons m be included in objects of

Object2 Object3

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES

Object1, Object2 and Object3 are all
objects of a Class Circle that are similar to i, j,
k are of integer data type in C language.

Saimple programs are given in VC++ D:\

C++ Program ‘execution.

Execution starts from main( ).

smallobj s1,s2;

Defines 2 objects s1,s2, of class smallobj.

Class smallobj doesn’t create any objects , but
describes how they look when they are created.
Space is set aside for it in memory.

S1.setdata(1066) ; //causes somedata set to 1066

. -> class member acess operator connects object
name and member function

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website

for students | VTU NOTES

C++ introduces a new keyword
class as a substitute for keyword struct .

structure members are public by
default

B.R.Mohan, SSE--> www.bookspar.com | Websit
for students | VTU NOTES

private:

int iFeet;

float finches;
Public:

void setFeet(int x)

{

iFeet=x;

}

float getFeet()

{

return iFeet;

}

int setInches(float y)

{

finches = y;

}

float getInches()

{ return fInches;

}

hs This can also be written as given in next slide

private:

int iFeet;
float finches;

void setFeet(int x)
{
iFeet=x;
}
float getFeet()
{
return iFeet;
}
int setInches(float y)
{
finches = y;
}
float getInches()
{ return fInches;

}

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

HAN member functions are public by default

for students | VTU NOTES

class members are private by
default

B.R.Mohan, SSE--> www.bookspar.com | Websit
for students | VTU NOTES

Private:

int iFeet;

float finches;
Public:

void setFeet(int x)

{

iFeet=x;

}

float getFeet()

{

return iFeet;

}

int setInches(float y)

{

finches = y;

}

float getInches()

{return fInches;

}

hs class members are private by default

int iFeet;
float finches;

Public:

void setFeet(int x)
{
iFeet=x;
}
float getFeet()
{
return iFeet;
}
int setInches(float y)
{
finches = y;
}
float getInches()
{ return fInches;

}

Prof. B.R.Mohan, SSE

private by default
//private by default

www.bookspar.com | Website
for students | VTU NOTES

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

ww.bookspar.com | Websit

U NOTE

Usually the data within the cl te and the functions that operate on
data are public so that they can be accessed from outside the class. Fig- for
publ ic & priva te

Class
Not accessible

From outside
Class

Accessible from
Outside class

for students | VTU NOTES
yntax of a Class specitier

Class Circle __, name of class

{ class is a keyword
private:

int data; private functions & data
public:

void DisplayRadius( );
void CalcArea( ); public functions & data
void CalcCircum( );

}

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

Differences between

C and C++
In C, umay / may not In C++, you must
Include function include function
Prototypes prototypes.
C++ lets you
specify default
values for
function‘s

parameters

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

C++ lets you

specify default
values for
function's
parameters in the
function's
protoype

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

Eg-

VaR Oyinelae@aratiohy—) | In C++, u may
Of a variable must place the

be at the beginning variable declara
Of the function tions close to
the statements

that use
variables before

using it in a
statement

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students |VTUNOTES:

If a C program uses a In C++, ucan
Local variable that has instruct prgm
Same name as global to use value of
Variable, then C program global variable
uses the value of a with scope
local variable. Resolution

operator

Eg-

cout << “lam

global var :

"<< cl

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

Lab Program-1

1s Given that Employee class contains
following

members: employeeno., empname, basic , da, it,

Netsalary and to print data members.

Write a C++ program to read the data of n

employees and compute netsalary of each

employee.(da=52%of basic and it =30% of gross

salary, netsalary=basic+da-it)

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

. Steps :
1. Define an Employee class and declare the given data
members.

2. Get the employee details using the member function
3. calculate netsalary of given employee using formula
display the resultant value

4. write the main function and create Employee objects. Call
member functions on the employee objects to read the data ‚to
calculate netsalary and to print the data members

Class:
. The class is a fundamental OOP concept in C++.

L A class declaration defines a new type that links
code(functions/operations) and data.

. This new type is then used to declare objects of that class.

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

- The class is a fundamental OOP concept in C++.

* Aclass declaration defines a new type that links
code(functions/operations) and data.

. This new type is then used to declare objects of
that class. Hence , a class is a logical abstraction,
but a physical existence.

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

Syntax:

class name objectname

object name.datamember; //access class members

object name.datamember; //calling mf on an object
Access specifiers:
public: allows fns / data to be accessible to other parts of ur
Pre
private: by default fuentions and data declared within a class
are private to that class and may be accessed only by public
members of the same class.

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

Class definition follows

Class Employee{

//declare data members here

int empno;

char empname[25];

float basic, da, it, netsal;

public:

void getdata();

void computenetsal(); void display();

};

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

Member functions

void employee::getdata() { //get emp details}
void employee::computenetsal() {
da=0.52*basic;

gross=basic-da;

it=0.3*gross;

//compute netsal

netsal=basic+da-it;

}

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

Void employee::display()
{

//display employee info on the monitor

i

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

2. Define a student class with Usn, name , marks in

3 tests of a subject. Declare an array of 10
student objects. Using appropriate functions, find
average of 2 better marks for each student. Print
usn, name and average marks of all students.

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

Steps For Il Programs

|. Define a Student class and declare the given
members.

Get the Student details using member functions to
get data

Find the average of 2 better marks for each student

4. Display resultant values — usn, name and average
marks of all students

»

uy

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

5. Write main() function and create an array
of 10 student objects. Call member functions on
student objects to read data to calculate average marks
and to print the student details along with average
marks.

Steps-
|. Define a student class and declare the given data
members

©

Get the student details using member function-
getdata()

3. Find average of 2 better marks for each student

4. Display the resultant values-usn, name and
average marks of all students

un

Write a main() & create an array of 10 student
objects. Call mfs of student objects to read data,

to calculate average marks & print the
student details along with their avg mks

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES
Lab Program-3

- Write a C++ program to create a class called
COMPLEX and implement following overloading
functions ADD that return a COMPLEX number.

1) ADD(a,s2) - where a is an integer (real part)
and s2 is a complex number.

11) ADD(s1,s2) — where s1, s2 are complex
numbers

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

Constructor :
1. Create a user defined datatype named as
COMPLEX. Declare the data members.
2. Initialize data members with default values. This

is a default constructor automatically invoked when an
object of type COMPLEX is defined / created.

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

3. Or initialize the data members with default values
specified while creating the object. This is a
Parameterized constructor, automatically invoked
when some initial values are passed as parameters
while creating an object.

4. Add an integer with a COMPLEX value

Add 2 COMPLEX objects overloading the ADD
function

un

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

6. Display the results directly or by overloading <<
operator
7. Write a main() function and call member functions

on the COMPLEX objects as required by the end
user.

for students | VTU NOTES
Friend Function

If u want to explicitly grant access to a
function that is not a member of current class,
declare that function a friend inside the class /
structure declaration.

Friend declaration occurs inside the class
because compiler reads class definition, size and
behaviour of data type

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

- Who can access my private implementation ?
Only friend functions can access private
Implementations

U cant break in from outside if u are not a friend.
Hence the operator << is overloaded to print the
complex number.

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES

Friend Functions

It is possible to grant nonmember function access
to the private members of a class by using a friend.

Friend function has access to all private and
protected members of the class for which it is a friend.

To declare a friend , include its prototype within
the class, preceding it with keyword friend

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

OBJECT ORIENTED
PROGRAMMING WITH C++

REVIEW OF STRUCTURES

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES

To understand procedural oriented
languages, we need to review structure
concept

Need for Structures — value of 1 variable
depends on the value of another variable.

Eg- Date can be programmatically
represented in C by 3 different int variables.

Say int d,m,y; d-date, m-month, y-year

Although 3 variables are not grouped in a code,
they actually belong to the same group. The
value of 1 may influence the value of other.
Consider a function nextday( ) that accepts the
addresses of 3 integers that represent a date
and changes these values to represent next day

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website

for students | VTU NOTES
Prototype of this function
{for calculating the next day
void nextday(int *,int *);
Suppose
d=1;
m=1;
y=2002; //1% january 2002
If we call nextday( &d, &m, &y);
D becomes 2, m=1,y=2002

for students | VTU NOTES
But if d=28;
m=2;
y=1999;//28 Feb 1999
and we call the function as

nextday( 8d, &m, &y);

d becomes 1, m will become 3 and y will
become 1999.

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES

y=1999;//31th Dec 1999

and we Call the function as
nextday( &d, &m, &y);
d will become 1 , m will become 1 and y
becomes 2000.
A change in 1 variable may change the
value of other 2.
No language construct exist that actually places
them in same group.

for students | VTU NOTES
Members of wrong group may be accidentally sent to
the function

d1=28; m1=2; y1=1999; //28thfeb99
d2=19; m2=3; y2=1999; //19thmrch99

nextday(&d1,&m1,&y1); //ok
nextday(&d1,&m2,&y2); //incorrect set passed

Above listing show problems in passing
groups of programmatically independent
but logically dependent variables

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

There is nothing in language itself that prevents the wrong set
of variables from being sent to the function. Suppose nextday()
accepts an array as parameter,

Then its prototype will be
void nextday(int *);
Let us declare date as an array of 3 integers.
int date[3];
date[0]-28;
date[1]-2
date[2]-1999; //28' Feb 1999

Let us call the function as follows
nextday(date);
The values of date[0],date[1],date[2] is set to 1,3
and 1999, respectively.
This method is not convincing. There is no data
type of date itself.

The solution to this problem is to create a datatype
called date itself using structures.

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website

for students | VTU NOTES

ruct date a1;

d1.d=28;

cl mes //Need for structures

d1.y=1999;

nextday(&d1);

d1.d, d1.m, d1.y will be set correctly to

1,3,1999, since the function takes the address
of an entire structure variable as parameter at
a time as there is no chance of variables of
different groups being sent to the function.

Structure is a programming construct in C that
allows us to put the variables together

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

Library programmers use structures to create new datatypes.
Application programs use these new datatypes by declaring
variables of this data type

struct date d1;

They call associated functions by passing these
variables / addresses to them.

d1.d=31;
d1.m=12;
d1.y=2003;
Nextday(&d1);

for students | VTU NOTES.
They use resultant value of the passed variable further
as per requirement

printf(“The next day is: %d
1d/%d\n”,d1.d,d1.m,d1.y);

O/P- The next day is:01/01/2004

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES

Creating a New Data Type using Structures

Creation of a new datatype is a 3 step process.

1. Put structure definition and prototypes of
associated functions in a header file.

2. Put the definition of associated functions in
a source code and create a library.

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

3. Provide the header file and library in any
media to other programmers who want to use
this new data type. Creating a structure and its
associated functions are 2 steps to constitute
one complete process

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

1. Putting structure definition and prototypes
of associated functions in a header file.

//date.h contains structure definition &
// prototypes of associated functions
Struct date
{

int d, m, y;
}
Void nextday(struct date *);

Void getsysdate(struct date *);

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES

2. put definition and other prototypes in a
source code and create a library

#include “date.h”

Void nextday(struct date *p)

{//calculate date represented by *p and set it to
“ph

Void getsysdate(struct date *p){ // determine
//current system date & set it to *p)

//definitions of other useful & other relevant
//functions to work upon vars of date structure

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES

Using Structures in Application Programs is a 3
step procedure

1. Include header file provided by programmer in
the source code.

2. Declare variables of new data type in the
source code

3. Embed calls to the associated functions by
passing these variables in the source code

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

4. Compile the Source code to get the object file.

5. Link the Object file with the library provided by
the library programmer to get the executable or
another library.

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

Step1-Include the header file provided by the
programmer inthe source code

//beginning of dateuser.c
#include “date.h”
void main()

{

}//end of dateuser.c

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

2: Declare variables of new data type in the
source code.

//beginning of dateuser.c

#include “date.h”

void main()

{ struct date d;

}//end of dateuser.c

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

3. Embed calls to associated functions by passing
these variables in source code

//beginning of dateuser.c

#include “date.h”

void main()

{ struct date d;

d.d=28; d.m=2; d.y=1999;
nextday(&d);

} //end of dateuser.c

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES

Procedure Oriented System has the following
programming pattern -

. Divides code into functions.

2. Data (contained in structure variables) is
passed from 1 function to another to be read
from or written into.

3. Focus is on Procedures / functions.
Procedures / functions are dissociated from
data & are not a part of it. Instead receive
structure variables / their addresses & work
upon them

Drawback/Disadvantage

1. Data is not secure and can be manipulated by
any function/procedure.

2. Associated functions that were designed by
library programmer don't have rights to work
upon the data.

3. They are not a part of structure definition itself
because application program might modify
the structure variables by some code
inadvertently written in application program
itself

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES

Consider an application of around 25,000 lines in which
the variables of structure is used quite extensively.

1. Testing may find that date being represented
by one of these variables has become 29' Feb
1999.

2. This faulty piece of code can be anywhere in
the program.

3. Hence Debugging will involve a visual
inspection of the entire code & will not be
limited to associated functions only.

4. While distributing his/her application,
application programmer cant be sure that
program would run successfully.

5. Every new piece of code accessing structure
variable will have to be inspected and tested
again to ensure that it doesn’t corrupt the
members of structure.

6. Compilers that implement procedure
oriented programming systems don’t prevent
unauthorized functions from accessing /
manipulating the structure variables.

7. To ensure a successful compilation of
his/her code, application programmer is
forced to remove those statements that
access data members of structure
variables.

8. Lack of data security of procedure oriented

programs has led to Object Oriented
Programming Systems

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES

Object Oriented Programming Systems

- Model real-world objects

+ RWO has internal parts & interfaces that
enable us to operate them.

Eg-LCD is RWO-has a fan and a lamp.

There are 2 switches 1 to operate fan & other
to operate lamp.

Switch operation has rules.

If lamp is switched on, fan is automatically
switched on, else Icd will be damaged.

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES

- Lamp is also switched off if fan is switched off
and switches are linked with each other.

Common Characteristic of RWO-

- If a perfect interface is required to work on an
object , it will have exclusive rights to do so.

+ Coming to C++, observed behaviour of LCD
projector resembles the desired behaviour of the
date’s structure variables.

- Compilers implementing OOPs enable data
security enforcing a prohibition by throwing
compile-time errors against the pieces of
code.

« RWO ensure a guaranteed initialization of
objects

OOPS Features —

1. Inheritance 2.
Polymorphism

for students | VTU NOTES
Inheritance allows one structure to inherit the
Characteristics of other structure.

variable of new structure will contain data
members mentioned in new structure definition.

Due to inheritance, it will also contain data
members in existing definition from which new
structure has inherited.

for students | VTU NOTES
In Inheritance, both data and functions may be
inherited

- Parent class can be given the general
characteristics, while its child may be given
more specific characteristics.

- Inheritance allows code reusability by keeping
code in a common place - the base structure.

- Inheritance allows code extensibility by
allowing creation of new structures that are
suited to our requirements compared to
existing structures.

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website

for students | VTU NOTES

nheritance — a process by which 1 object can
acquire the properties of another object.
This is important as it supports classification

Most knowledge is made of hierarchical

Classification.

Eg-Red delicious apple is part of apple
classification which in turn is a part of fruit class,
which is under the larger class food.

Inheritance mechanism makes it possible for one
object to be a specific instance of a more general
class.

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES

Polymorphism

Using operators or functions in different ways
depending on what they are operating on is
called Polymorphism

Static & Dynamic Polymorphism

Function overloading & OperatorOverloading

for students | VTU NOTES
‘ ;
Function Prototyping

- FP is necessary in C++.

- C++ strongly supports function prototypes

+ Prototype describes the function’s interface to the
compiler

- Tells the compiler the return type of function, number,
type and sequence of its formal arguments

GENERAL SYNTAX OF FUNCTION
PROTOTYPE

return_type function_name( argument_list);
Eg-
int add ( int, int);

indicates add() function returns a int type and takes
2 arguments both of int type and terminates with ;

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

With prototyping , compiler ensures following

1. The return value of a function is handled
correctly.

2. Correct number and type of arguments are
passed to a function.

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

Since C++ compiler require function
prototyping, it will report error against function call
because no function prototype is provided to resolve
the function call.

Compiler may still give an error, if function call
doesn’t match the prototype.

Hence prototyping guarantees protection from
errors arising out of incorrect function calls

Sometimes function prototype & function call
may not match

FD and FP are both created by Library
programmer.

He/She puts FP in a header file , puts FD ina
library.

Application programmer includes header file
in his/her application program file in which function
is called.

He creates an object file from application file
and links this object file to the library to get an
executable file.

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

Function Prototyping produces automatic type of
conversion. Wherever appropriate

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website

for students | VTU NOTES

Objects — Variables of classes are
known as Objects

SCOPE RESOLUTION OPERATOR (SRO) —

It is possible and necessary for Library
programmer to define member functions
outside their respective classes.

SRO makes this possible. Example
illustrates the use of scope resolution operator

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

class Distance
{

int iFeet;

float finches;
public:
void setFeet(int); //only member function
int getFeet(); //prototypes are given
void setinches(); //in the class definition.
float getinches();

y

for students | VTU NOTES

Member Functions are prototyped within the
class and have been defined outside
void Distance :: setFeet (int x)//definition
{

iFeet=x;
}
int Distance :: getFeet() //definition
{return iFeet;

}

for students | VTU NOTES
void Distance :: setInches (int y) //definition

{
}

int Distance :: getInches() //definition

{

fInches=y;

return fInches;
} code showing use of scope resolution operator
that specifies class to which member function belong.
The class name is specified on LHS of SRO and
name of member function being defined is on the
right hand side

Creating Libraries using the Scope
Resolution Operator

Creating a New Data type
/ class is also a 3 step Process
i.e. executed by the
Programmer.

Step-1. Place the class definition in a header file.

Step-2. Place the definitions of member
functions in a C++ source file / library source code /

class implementation file.

Step-3. Provide header file and library file in any
media to other programmers who want to use this
new datatype.

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website

_ for students | VTU NOTES

//Distance.h- header file containing Distance class

class Distance

{
int iFeet;
float fInches;
public:
void setFeet(int); /fonly member function
int getFeet(); //prototypes are given

void setInches(); //in the class definition.
float getInches();
$5

www.bookspar.com | Website

is | VTU NOTES

Step-2. Place the definitions of member
functions in a C++ source file / library source
code / class implementation file

/limplementation file for class Distance —
//Distlib.cpp

for students | VTU NOTES
void Distance :: setFeet (int x)//definition
{
iFeet=x;
}
int Distance :: getFeet() //definition
{ return iFeet;

}

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

Void Distance:: setinches (int y) //definition

{

iFeet=x;

int Distance::getinches() //definition
{

return finches;

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

Step-3. | Provide header file and library file in
any media to other programmers who want to
use this new datatype.

Using classes in the
Application Programs
The five steps followed by
Programmers for using this
new datatype / class are —

for students | VTU NOTES
Step-1. Include the header file provided
by the programmer in their source code

/Idistmain.cpp
#include “Distance.h”
void main()

Lan

} //end of Distmain.cpp

for students | VTU NOTES
Step-2. Declare variables of the new
datatype in their source code

//Distmain.cpp
#include “Distance.h”
void main()

{
Distance d1,d2;

} //end of Distmain.cpp

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website

for students | VTU NOTES

Step-3 Embed calls to the associated
functions by passing these variables in their
source code

Listing in next slide shows how to use
classes in the application programs

Prof. B.R.Mohan, SSE--> www. a com | Website

for students

distmain.cpp- À sample driver program or creating and
using objects of class Distance

#include<iostream.h>

#include “Distance.h”

void main()

{Distance d1,d2;

di.setFeet(2); d2.setinches(2.2);
di.setFeet(3); d2.setinches(3.3);

cout << d1.getFeet() << “ “ << d1.getinches();
cout << d1.getFeet() << “ “ << d2.getinches(); }

}

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES

Step-4 Compile the source code to get the
the object file.

Step-5 Link the object file with the library
provided by the library programmer to
get the executable or any library.

Output - 2 2.2

3 3.3
Implementation files are compiled and
converted into static and dynamic libraries

for students | VTU NOTES
The ‘this’ pointer-The facility to create and call member functions
of class objects is provided by
the compiler. Compiler does this by using a unique pointer -> this

this pointer - always a constant
pointer.
- points at the object with
respect to which the
function was called

for students | VTU NOTES
Working of this pointer-

Once the compiler is sure that no attempt
is made to access the private members of
an object by nonmember functions, it
converts C++ code into an ordinary code as
Follows.

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

1. It converts class into structure with only
data members as follows
Before

class Distance
{

int iFeet;

float fInches;
public:
void setFeet(int); //fonly member function
int getFeet(); //prototypes are given
void setInches(); {fin the class definition.
float getInches();
b

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

Struct Distance

{
int iFeet;
float finches;

b

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website

for students | VTU NOTES

puts a declaration of the this pointer as a leading
formal argument in the prototypes of all member
functions as follows
Before —
void setFeet(int);

After -
void setFeet( Distance * const int);

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

void getFeet()

After —

void getFeet(Distance * const );
Before —

void setinches( float);

After —

void setInches(Distance * const, float);
Before —

float getInches();

After —

float getInches(Distance * const);

for students | VTU NOTES

3. It puts the definition of this pointer as a
leading formal argument in the definitions
of all member functions as follows

It also modifies all statements to
access object members by accessing
through the this pointer using the pointer-
to-member access operator (->).

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

Before —
void Distance :: setFeet ( int x)

{

iFeet = x;
}
After —
void setFeet( Distance * const this, int x)
{
this -> iFeet = x;

}

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

Before —

int Distance :: getFeet()
{ return ¡Feet; }

After —

int getFeet( Distance * const this)
{ return this -> iFeet; }

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

Before —

void Distance :: setInches (float y)

{fInches = y; }

After —

Void setInches(Distance * const this, float y)

this -> flnches = y;

}

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

Before —

float Distance :: getinches ()

{ return flnches; }

After —

void getInches(Distance * const this)

{

return this -> finches;

for students | VTU NOTES
SRO - operates on its operands.
- binary operator taking 2

Operands. . | o
» Operand on its left is the name of a predefined class. Right is a
member function of the class.

+ Based on this info, SRO inserts a constant operator of correct type
as a leading formal argument to function on its right.

4. Passes the address of ieee en as RE
parameter to each call to the member function as
follows

Before —

D1.setFeet(1);

After -

setFeet(&d1, 1);

Before —

d1.setinches(1.1);

After —

setinches(3d1 , 1.1);

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

Before —
cout << d1.getFeet() << endl;
After —
cout << getFeet(&d1) << endl;
Before —
cout << d1.getInches() << endl;
After —
cout << getinches(&d1) << endl;
In case of C++, dot operator's
definition is extended

Prof. B.R. Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES
continue to point at same object

— the object with respect to which the member Function has
been called

— throughout the lifetime.

Hence the compiler creates it as a
constant pointer.

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website

for students | VTU NOTES

The accessibility of the implicit object is similar to the
other objects passed as parameters in function call
and local objects inside that function

Anew function — add() has been added to
the existing definition of the class

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website

for students | VTU NOTES
{
int iFeet;
float finches;
public:
void setFeet(int); //only member function
int getFeet(); {prototypes are given
void setinches(); //in the class definition.
float getinches();
Distance add( Distance);
b

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website

dd) for students | VTU NOTES

{ Distance temp;
temp.iFeet = iFeet+dd.iFeet;
temp.finches=finches+ dd.finches;
return finches;

}
described conversion for this add() using this ptr

Distance add( Distance * const this dd)

{ Distance temp;
temp.iFeet = this->iFeet+dd.iFeet;
temp.finches=this->finches+ dd.flnches;
return finches;

}

A statement d3=d1.add(d2) is invoked as

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

emp

Temp.iFeet

d3=d1.add(d2);
di
d2

Data in temp is
assigned to d3
using temp in
add(d2) function

Similarly d1.iFeet, d1.flnches. D2.fInches, d2.iFeet can be accessed

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website

for students | VTU NOTES

xplicit Address Manipulation

An Application Programmer can manipulate the
member data of any object by explicit address
manipulation. Like Dot ,arrow operator is also extended
in C++. Arrow operator takes data members and
member functions as its right hand side operand.
Astatement
dptr -> setFeet(1); after conversion becomes
setFeet ( dptr, 1);

The value of dptr is copied into ‘this’ pointer.

Hence this pointer also points at the same object at
which dptr points //d01.cpp,d11.cpp

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
Calling 1 Te er actor
from another

1 member function can be called from another. The
call to the A :: setxindirect() function changes from

A1.setxindirect(1); //c++ call
To

setxindirect(&A1,1); //c call

Prof. B.R.Mol in Sn -> www.bookspar.com | Website
students | VTU NOTES

Function Definition Of À :: : setxindirect() function
changes from

void A :: setxindirect( int q)
|

setx(q);
} to
void A :: setxindirect( A * const this, int q)
{

this -> setx(q); //calling function through pointer

}

that changes to

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

void A :: setxindirect( A * const this, int q)

{

setx(this,q); //action of arrow operator

}

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

Member Functions and Member Data

We see different types of member data &
member functions that classes in C++ have

Member functions can be overloaded just like
nonmember functions.
Code d14.cpp illustrates the point.

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website

for students | VTU NOTES

Function Overloading enables us to have 2 functions of same
name and same signature in 2 different classes illustrated below.

Class A

{

Public:

void show();

H
Class B
{
Public:

void show();

A

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

Knowledge of this pointer tell the signatures of
show() are different

Function prototypes in respective classes are
void show(A* const);
void show(B* const);

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

Default Values for Formal Arguments
of Member Functions

Default values can be assigned to arguments of
non-member functions and member functions.
Member functions should be overloaded with care. If
default values are specified for some or all of its
arguments. D15.cpp
For example- Compiler will report an ambiguity error
when it finds the second prototype for the function for
show() of class A as follows. Class A
{ public:
void show();
void show(int =0);
}; /d17.cpp

Reasons for Ambiguity

In case of nonmember functions, if default
values are specified for more than 1 formal
argument, they must be specified from right to
left.

Default values must be specified in the
function prototypes, not in function definitions.
Further default values can be specified for formal
arguments of any type.

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES

Member functions are made inline by 2
Methods.

1. By defining function within the class
itself.
2. By only prototyping and not defining the
function within the class. The function is
defined outside the class using Scope
Resolution Operator. The definition is prefixed by inline

keyword. As in noninline member functions, the definition

of inline function must appear before the function is
called.

Hence the function should be defined in the same
header file in which the class is defined.

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

Class Distance
{ int iFeet, flnches; //private by default
Public:
void setFeet(int x)
{ ¡Feet =x; }
int getFeet() { return iFeet; }
Void setinches(float y) { return flnches; }
float getInches() {return flnches; }

//meminline.cpp
Class A
{

public:

void show();

E
Inline void A :: show() //definition in header file
{
//definition of A :: show() function
}

Inline member Functions

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES
Ü

The Library Programmer may desire that one of member functions
of his/her class shouldn't be able to change the value of member
Data.

Function should merely read values contained in the data
Members, but not change them even accidentally while defining the
function.

Compiler’s help may be sought by declaring function as constant
Function & attempting to change data value through member
Function, the compiler may throw an error.
getFeet() & getInches() and add() of Distance class should obviously
be constant functions and shouldn't change the ¡Feet / finches
members of invoking object even by accident.

Member functions are specified as constants by suffixing prototype
And function definition header with const keyword.
Modified Distance class is written as

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

Class Distance
{ int iFeet; float flnches;
public:
void setFeet(int);
int getFeet() const; //constant function
void setinches(float);

float getInches() const; //constant function
Distance add(Distance) const; //constant function

{ iFeet=x; }

void Distance::getFeet() const //const function
{ iFeet++; //ERROR!!

return iFeet; }

void Distance::setinches(float y)

{ fInches=y; }

void Distance::getInches() const //const function
{ flnches=0.0; — //ERROR!!

return flnches;

}

Prof. B.R,Mohan, SSE--> www,bookspar.com | Website

for students] VI UNO TES:
{
Distance temp;
temp.iFeet= iFeet + dd. iFeet;
temp.setinches (flnches + dd.flnches);
iFeet++; //ERROR!!
return temp;
}

For const. member functions, memory occupied by invoking
object is a read-only memory. Only const. member functions can
be called with respect to constant objects.

However nonconstant functions can be called with respect to
nonconstant objects.

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website

for students | VTU NOTES

VUutable Data Members

Mutable data member is never constant.
i. It can be modified inside constant functions also.

2. Prefixing the declaration of a data member with the key
word mutable makes it mutable. Code shows in next slide

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES

ass À mutable.

{

int x;
mutable int y;
public:
void abc() const //a constant member function
{ //error: cant modify a non-constant da
x++; //ta member in a const. mf
y++;//0k can modify a mutable data member in
// const. mf
void def) //non-const. mf
{ x++; //ok can modify nonconstant data member

{lin a non-const. mf
y++; //ok can modify mutable data member in a
//nonconst.mf } i
/*end of mutable.h*/

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website

for students | VTU NOTES
We frequently need a data member that can be

modified even for constant objects.

Suppose there is a member function that saves the data of
an invoking object in a disk file. This function should be
declared as a constant to prevent even an inadvertent change
to the data members of the invoking object.

If we need to maintain a flag inside each object that tells
whether the object has already saved or not, such data should
be modified within above constant member function.

Hence this data member should be declared a mutable
member.

for students | VTU NOTES
Friends- A class can be global non-member function and member functions of
other classes as friends.
Such functions can directly access private data members of objects of
class.

Friend Non-member functions

a Friend function is a non-member function that has
special rights to access private data members of any
object of class of whom it is a friend.

Here we study only those friend functions that are
not member functions of some other class.

Friend function is prototyped within the definition of
Class of which it is intended to be friend.

It is prefixed with the keyword friend.

Since it is a non-member function, it is defined without

using scope resolution operator. It is not called with respect to
an object.

for students | VTU NOTES
Friend Functions

» Friend keyword should appear in the prototype only and
not in the definition

+ Since it is a nonmember function of the class of which it
is a friend, it can be prototyped in either private or public
section of the class.

- A friend function takes 1 extra parameter compared to a
member function that perform a same task

» No need of using scope resolution operator for defining a
member function.

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

- Friend functions don't contradict the principles of
OOPs.

- The benefits provided by data hiding are not
compromised by friend functions.

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES

Friend Classes

» A class can be friend of another class. Member
Functions of a friend class can access private data
members of objects of class of which it is a friend.
If class B is made a friend of class A, example illustrates this
Class A
{friend class B; //declaring class B as a friend of class A
/* rest of class A*/ //doesn’t matter to declare in priv or
//public section for friend function
};

fig- declaring friend classes

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website

for students | VTU NOTES

Member functions of class B can access private
members of objects of class A

Listing the effect declaring a friend class frie

Class B; // forward declaration needed because
/Idefinition of class B is after stmt declaring

/Iclass B is a friend of class A
Class A
{int x;
Public:
void setx(const int =0);
void getx() const;
friend class B; //declaring class B as a friend of A

ll

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

ass B
{ A* Aptr;
Public:

void Map(const A * const);
void test_friend( const int);

}

void B :: Map(const A*, const p);
{

Aptr=p;

}

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

Void B :: test_friend(int i)
{

Aptr -> x=i; //accessing private data member

}

Code effect of declaring a friend class

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

- Member functions of class B are able to access private
data member of objects of class A although they are not
member functions of class A. This is because they are
member functions of class B i.e. a friend of class A.

- Friendship is not transitive.
+ Consider the listing in next slide

for students | VTU NOTES

Class B; //friendtran.cpp
Class C;
Class A
{

friend class B;

int a;
y
Class B
{

friend class C;

A

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

Class C

{

void f( A *p)

{

p->a++; /lerror: C is not a friend of A despite
// being a friend of friend

}
y
//end of friendtran.cpp

Code to show that friendship is not transitive

for students | VTU NOTES
Friend Member Functions

Can we make specific member functions of 1 class
friendly to another class ?

For making only ‘ B:: test_friena() ’ function a friend
of class A, replace the line
Friend void B::test_friend();

The modified definition of class A is given in next slide

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES

ass A
{
/*rest of class A
Friend void B :: test_friend();
b
To compile this code successfully, compiler should first

see definition of class B, else it doesn’t know that
test_friend() is a member function of class B.

However, a pointer of type À * is a private member of
class B.

This problem of circular dependence is solved by
forward declaration by inserting a line

Class A; //Declaration ‚only not definition!
before definition of class B. declarations and
definitions of 2 classes appear in next slide.

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES
riendmemfunc.

class A;
class B
{

A *Aptr;
Public:

void Map(const A * const);

void test_friend(const int=0);
i
class A
{

int x;

public:

friend void B :: test_friend ( const int=0)

Forward declaring a class that requires a friend.

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website

for students | VTU NOTES

ass A;
Class B
{
A *Aptr;
public:
void map(const À *A);
void test_friend(const int =0);
b
Class A
{int x;
Public: friend void B:: test_friend(const int =0);
} inline void B:: test_friend( const p)
{
Aptr->x=p;

}

Static Data Members — hold global data i.e.

common to all objects

Examples of such global data are —
1. Count of Objects currently present
2. Common data accessed by all objects, etc.

onsider class Account and we may
Want all objects to calculate interest rate
at 4.5%.
Hence this data should be available
globally to all objects of this class.
This data should be stored globally to
All objects of this class.

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES
O

variables. They can also be passed by reference to
Functions.

Finally they can be returned by value or by reference
from the functions.

Distloc.cpp, distarray.cpp largedist.cpp

Prof. B.R.Mohan > www.bookspar.com | Website

for ts |VTU NOTES
class. Such an array becomes a member all objects of class. It can be
accessed / manipulated by all member functions of the class.

#define SIZE 3
/*A class to duplicate the behavior of an integer array*/
class A
{
int iArray[SIZE];
Public:
void setElement (unsigned int, int);
int getElement (unsigned int);

};

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website

10? Stadenis NVI NOTES
At position passed as first parameter*/
void A::setElement(unsigned int, int)
{ if (p<=SIZE)return; //better to throw an exception
¡Array[p]=v;
)

/*function to read the value from the position passed as
parameter*/

int A::getElement(unsigned int p)

{ if (p<=SIZE)return -1; //better to throw an exception
return ¡Array[p];

}

code for arrays inside the objects, always better to throw
exceptions rather than terminating the functions

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES 2

global namespace that lead to name clashes
Global namespace refer to the entire source code. It
Includes all the directly and indirectly included header files.

By default, name of each class is visible in the source code
i.e. in the global space. This can lead to problems.

Suppose a class with same name is defined in 2 header files.
/*A1.h*/
class A
o
class B
th

Lets include both these header files in a program and see what
happens if we declare objects of the class

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES
#include “A1.h”
#include “A2.h”

void main()

{ AAobj; //Ambiguity error due to multiple definitions of A

}

Code showing a reference to a globally declared class can lead to
ambiguity error.

Global visibility of definition of class A make the inclusion of 2 header
Files mutually exclusive. Consequently, this makes use of 2 definitions of
class A mutually exclusive.

An application accesses both definitions of class A simultaneously by
enclosing 2 definitions of the classin separate namespaces can overcome
this problem.

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
A for students | VTU NOTES

namespace A1

{

class A

{ }

} /*end of namespace A1.h*/

/*A2.h*/
namespace A2

{

class A

{ }

} /*end of namespace A2.h*/

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website

OPIO NOD be.
VETOUDEU ú

Namespaces.
Corresponding namespaces, followed by SRO, must be
prefixed
to the class name while referring to It anywhere in the source
code. Hence the ambiguity encountered in above listing can be
overcome.
Revised definition of main() function
#include “A1.h”
#include “A2.h”
void main()
{ A1::A Aobj1; //ok: Aobj1 is an object of class defined in A1.h
A2::A Aobj2; //ok: Aobj2 is an object of class defined in A2.h

} enclosing classes in namespaces prevent pollution of
namespaces

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students INTUNOTES,

can be cumbersome.

The using directive enable us to make class definition inside
A namespace visible so that qualifying the name of referred
Class by name of namespace is no longer required. Code below
tells how this is done
/*using.cpp*/

#include “A1.h”

#include “A2.h”

void main()

{ using namespace A1;

A1::A Aobj1; //ok: Aobj1 is an object of class defined in A1.h
A2::A Aobj2; //ok: Aobj2 is an object of class defined in A1.h

} using directive makes qualifying of referred class names by
names of enclosing namespaces unnecessary

Using directive brings back global namespace pollution
That namespaces mechanism was supposed to remove in the
first place!

The last line in above listing compiles only because the
classname was qualified by the name of namespace.

Having long name for namespaces. Qualifying the name of a
class i.e. enclosed within such name of namespace is
cumbersome

name_space a_very_very_long_name
{ class A
UE
}
void main()
{a_very_ very long_name::A A1; //cumbersome long name

} Assigning a suitably short alias to such a long name solves the
problem

/*longname2.cpp*/

name_space a_very_very_long_name
{class A { H

}

namespace x=a_very_very_long_name;

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
g for students | VTU NOTES

name_space a_very_very_long_name
[ class A { };
}

namespace x=a_very_very_long_name;

Void main()

{

X::A A; //convenient short name

}

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website

=... for students |VTUNOTES =
number of places i in ithe s source code. Changing the alias declaration so that it stands: as
an alias for a different namespace will make each reference of enclosed class refer to a
completely different class
Suppose an alias x refers to a namespace ‘N1’.
namespace x = Ni; //declaring an alias

Further suppose this alias has been used extensively in code
X::A Aobj; //Aobj is an object of class A i.e. enclosed in namespace N1
Aobj.f1(); //f1() is a member function of above class

If declaration of alias is changed to namespace N2,
Namespace x=N2;

Then all existing qualifications of referred class names that use x would now
refer to a class Ai.e. contained in namespace N2.

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

Nested Classes — A class can eb defined inside another class.
Such a class is called Nested class. A class that contain a nested class is
called Enclosing class. Nested classes are defined in private, protected,
or public portions of enclosing class
- Class B is defined in the private section of the class.
/*nestedprivate.h*/
Class A
{
class B
{ /* definition of class B*/
{/* definition of class A*/
}; “end of nestedprivate.h*/ Nested classes

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

Here class B is defined in public section of class A.
Anested class is created if it doesn't have any relevance
outside its enclosing class. Naming Collision can be avoided with nested class

Class A /*nestpublic.h*/
{
public:
class B
{/* definition of class B*/
y
/*definition of class A*/
$» A public nested class

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES

In the listings of the 2 slides , even If there is aclass B
defined as A global class, its name will not clash with the
nested class B.

The size of objects of an enclosing class is not affected by
the presence of nested class. //size.cpp

How are members of a nested class defined ?

Members of a nested class can be defined outside the definition
of the enclosing class by prefixing the function name with name of
enclosing class followed by SRO. This inturn is followed by name

of nested class followed again by SRO.

for students | VTU NOTES

{

public:

class B

{ public:

void BTest(); //prototype only

5 //definition of class A
}
#include “nestclassdef.h”
void A::B::BTest()
{ //definition of A::B::BTest() function
}
/* definition of rest of functions of class B*/
Code Defining member functions of nested classes

for students | VTU NOTES
Anested class may be only prototyped within its enclosing class
and defined later. Again , name of enclosing class with SRO is required.

Class A /nestclassdef.h

{ class B; //prototype only

y

Class A::B

{ /*definition of the class B*/

}

Defining a nested class outside the enclosing class.

Objects of nested class are defined outside the member functions
of the enclosing class followed by SRO(scope resolution
operator) A::B B1; line will compile only if class B is

defined within public section of class A, else compile
time error occurs

Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES

An Object of the nested class an be used in any of the
member functions of the enclosing class without the
scope resolution operator. Moreover an object of nested
Class can be a member of enclosing class.

In either case ,only the public member functions of the object
can be accessed unless the enclosing class is a friend of the
nested class

Prof. B.R.Mohan, SSE-> www.bookspar.com | Website
for students | VTU NOTES

Class A
{
class B
{
public:
void ATest();
}
i //nestclassobj.cpp
#include “nestclassobj.h”
void A::ATest()
{ B1.BTest();
BB2;
B2.BTest();
Declaring objects of nested class in the member functions of the
enclosing class

www.bookspar.com | Website

is | VTU NOTES
members of the enclosing class through an object, a pointer, or a reference
only.

//enclclassobj.h
Class A
{
Public:
void ATest();
class B
{
public:
void BTest();
void BTest1 ();

for students | VTU NOTES
enciclassobj.cpp

#include “enclclassobj.h”

void A::B::BTest(A& ARef)
{ ARef.ATest() /lok

}

void A::B::BTesti ()

{

ATest(); //Error
}

Accessing nonstatic members of the enclosing the class in
member functions of the nested class.

Hoe Stils IS
Access is made to the member of the enclosing class
through the function of the nested class.

CREATION OF AN OBJECT OF ANESTED CLASS DOES
NOT CAUSE AN OBJECT OF ENCLOSING CLASS TO BE
CREATED.

The classes are nested to merely control the visibility.
Since A::B::BTest() function will be called with respect to an object

Of class B, a direct access to a member of the enclosing class A
can be made through an object of that class only.