OOPS Introduction

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 186

OOC

OBJECT
OBJECT ORIENTED
ORIENTED
PROGRAMMING
PROGRAMMING WITH
WITH C+
C+
++
B.R.MOHAN
CSE DEPT
SSE, MUKKA
OOC

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

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

2. The Complete Reference C++,


Herbert Schildt, 4th Edition, TMH, 2005
OOC

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

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

8. Stream Handling
Unit-6
9. Stream Handling contd 10. Operator
Overloading
OOC

Unit-7:
11. Operator Overloading contd.

Unit-8:
12. Type Conversion, New style
casts, and RTTI
13. Templates FT,CT, STL
14. Exception Handling
OOC

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.
OOC

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
OOC

• 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.
OOC

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.
OOC

Drawbacks/Disadvantages of Procedural languages.

1. Data is undervalued – given II 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
OOC

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
OOC

Accessible by
Global Variable
any function

Accessible by Accessible by
Function A Function B

Local Var Local Var

Function A Function B
GlobalData Global Data Global Data Global Data

Fn A Fn A Fn A Fn A
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.
OOC

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
OOC

• 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.
Organization Of a C++ Program OOC

Fig – Object Oriented Paradigm

object
Data

MF

MF
Object Object

Data
Data
MF
MF

MF
MF
OOC

Corporate Paradigm

CSE Dept Sales Data

Sales Manager

Secretary

Finance
Dept
Personnel
Dept
Personnel Data
Finance Data

Personnel Manager
Finance Manager
Personnel Staff
Financial Assistant
OOC

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
OOC

A Class serves as a plan / template like structure,


specifies what data & functions will be included in objects
of the class. Fig- A Class & its Objects
Class Circle
Feature A Feature B

Feature C
Specifications for class
Circle
Object1 Object2 Object3

Class Circle
Feature A Feature B
Class Circle Class Circle
Feature A Feature B Feature A Feature B
Feature C

Feature C Feature C
OOC

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:\
OOC

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
OOC

C++ introduces a new keyword


class as a substitute for keyword
struct .

structure members are public by


default
Struct Distance OOC
{
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;
}
}; This can also be written as given in next slide
Struct Distance OOC
{
private:
int iFeet;
float fInches;

void setFeet(int x) //All member functions are public by default


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

class members are private by


default
class Distance OOC
{
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;
}
}; class members are private by default
class Distance OOC
{

int iFeet; //private by default


float fInches; //private by default
Public:
void setFeet(int x)
{
iFeet=x;
}
float getFeet()
{
return iFeet;
}
int setInches(float y)
{
fInches = y;
}
float getInches()
{ return fInches;
}
};
OOC

Classes and Objects


Classes contain Data and Functions

Class Data1
Data2
Data3

Data
Function

Fn1
Fn2
Fn3
OOC
Class can contain private and public.
Usually the data within the class is private and the functions that
operate on data are public so that they can be accessed from outside
the class. Fig- for public & private
Class
Not accessible private
From outside
Class
Data or Functions

Accessible from
Outside class public

Data or Functions
OOC

Syntax of a Class Specifier


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( );
};
OOC

Differences between
C and C++
In C, u may / may not In C++, you must
Include function include function
Prototypes prototypes.
C++ lets you
specify default
values for
function‘s
parameters
OOC

C++ lets you


specify default
values for
function‘s
parameters in the
function’s
protoype
OOC

Eg-
void myfunction(int
In C, x=3,int y=4)
the declaration 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
OOC

If a C program uses a In C++, u can


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 << “Iam
global var :
” << ::I;
OOC

Lab Program-1

1. 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)
OOC

• 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++.
• 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.
OOC

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


• 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. Hence , a class is a logical abstraction,
but a physical existence.
OOC

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
Prg
private: by default fucntions and data declared within a class
are private to that class and may be accessed only by public
members of the same class.
OOC

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();
};
OOC

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;
}
OOC

Void employee::display()
{
//display employee info on the monitor
}
OOC

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.
OOC

Steps For II Programs


1. Define a Student class and declare the given
members.
2. Get the Student details using member functions to
get data
3. Find the average of 2 better marks for each student
4. Display resultant values – usn, name and average
marks of all students
OOC

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.
OOC

Steps-
1. Define a student class and declare the given data
members
2. 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
5. 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
OOC

Lab Program-3
• Write a C++ program to create a class called
COMPLEX and implement following overloading
functions ADD that return a COMPLEX number.
i) ADD(a,s2) - where a is an integer (real part)
and s2 is a complex number.
ii) ADD(s1,s2) – where s1, s2 are complex
numbers
OOC

Steps for LAB PRG III


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.
OOC

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
5. Add 2 COMPLEX objects overloading the ADD
function
OOC

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.
OOC

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
OOC

• 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.
OOC

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
OOC

OBJECT ORIENTED
PROGRAMMING WITH C++
REVIEW OF STRUCTURES
OOC

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
OOC

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
OOC

Prototype of this function


//for calculating the next day
void nextday(int *,int *);
Suppose
d=1;
m=1;
y=2002; //1st january 2002
If we call nextday( &d, &m, &y);
D becomes 2, m=1,y=2002
OOC

But if d=28;
m=2;
y=1999;//28th Feb 1999
and we call the function as

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


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

Again if d=31;
m=12;
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.
OOC

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
OOC

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; //28th Feb 1999
OOC

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.
OOC

Struct date d1;


d1.d=28;
d1.m=2; //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
OOC

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);
OOC

They use resultant value of the passed variable


further as per requirement
printf(“The next day is: %d
/%d/%d\n”,d1.d,d1.m,d1.y);
O/P- The next day is:01/01/2004
OOC

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.
OOC

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
OOC

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 *);
OOC
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
*p}
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
OOC

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
OOC

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.
OOC

Step1-Include the header file provided by


the programmer in the source code
//beginning of dateuser.c
#include “date.h”
void main()
{


} //end of dateuser.c
OOC

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
OOC

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
OOC

Procedure Oriented System has the following


programming pattern -
1. 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.
4. Procedures / functions are dissociated from
data & are not a part of it. Instead receive
structure variables / their addresses & work
upon them
OOC

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
OOC

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 th 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.
OOC

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.
OOC

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
OOC

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 lcd will be damaged.
OOC

• 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.
OOC

• 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
OOC

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.
OOC

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.
OOC

Inheritance – 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.
OOC

Polymorphism

Using operators or functions in different ways


depending on what they are operating on is
called Polymorphism
Static & Dynamic Polymorphism
Function overloading & OperatorOverloading
OOC

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
OOC

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 ;
OOC

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.
OOC

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
OOC

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 in a
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.
OOC

Function Prototyping produces automatic type of


conversion. Wherever appropriate
OOC

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
OOC

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();
};
OOC

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;
}
OOC

void Distance :: setInches (int y) //definition


{
fInches=y;
}
int Distance :: getInches() //definition
{
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
OOC

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.
OOC

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.
OOC
Step-1. Place the class definition in a header file.

//Distance.h- header file containing Distance class

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();
};
OOC

Step-2. Place the definitions of member


functions in a C++ source file / library
source code / class implementation file

//implementation file for class Distance –


//Distlib.cpp
OOC

void Distance :: setFeet (int x)//definition


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

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


{
iFeet=x;
}
int Distance::getInches() //definition
{
return fInches;
OOC

Step-3. Provide header file and library file in


any media to other programmers who want to
use this new datatype.
OOC

Using classes in the


Application Programs
The five steps followed by
Programmers for using this
new datatype / class are –
OOC

Step-1. Include the header file provided by


the programmer in their source code
//distmain.cpp
#include “Distance.h”
void main()
{ ….
….
} //end of Distmain.cpp
OOC

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
OOC

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
OOC

//distmain.cpp- A sample driver program for creating


and using objects of class Distance

#include<iostream.h>
#include “Distance.h”
void main()
{Distance d1,d2;
d1.setFeet(2); d2.setInches(2.2);
d1.setFeet(3); d2.setInches(3.3);
cout << d1.getFeet() << “ “ << d1.getInches();
cout << d1.getFeet() << “ “ << d2.getInches(); }
}
OOC

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
OOC

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
OOC

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.
OOC

1. It converts class into structure with only


data members as follows
Before
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();
};
OOC

After
Struct Distance
{
int iFeet;
float fInches;
};
OOC

2. It 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);
OOC

Before –
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);
OOC

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 (->).
OOC

Before –
void Distance :: setFeet ( int x)
{
iFeet = x;
}
After –
void setFeet( Distance * const this, int x)
{
this -> iFeet = x;
}
OOC

Before –

int Distance :: getFeet()


{ return iFeet; }
After –

int getFeet( Distance * const this)


{ return this -> iFeet; }
OOC

Before –
void Distance :: setInches (float y)
{ fInches = y; }
After –
Void setInches(Distance * const this, float y)
{
this -> fInches = y;
}
OOC

Before –
float Distance :: getInches ()
{ return fInches; }
After –
void getInches(Distance * const this)
{
return this -> fInches;
}
OOC

SRO - operates on its operands.


- binary operator taking 2
operands.
• 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.
OOC

4. Passes the address of invoking object as leading


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(&d1 , 1.1);
OOC

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
Its evident that ‘this’ pointer should
OOC

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.
OOC

The accessibility of the implicit object is similar to


the other objects passed as parameters in function call
and local objects inside that function
A new function – add() has been added to
the existing definition of the class
class Distance //Distance.h OOC

{
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);
};
Distance add( Distance dd) OOC

{ 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.fInches;
return fInches;
}
A statement d3=d1.add(d2) is invoked as
OOC

temp
Temp.iFeet
iFeet
Temp.fInches Data in temp is
fInches assigned to d3
using temp in
add(d2) function
d3=d1.add(d2);
d1
d2

iFeet
iFeet
fInches
fInches

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


OOC

Explicit 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.
A statement
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
OOC

Calling 1 member function


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


OOC

Function Definition of A :: 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
OOC

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


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

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.
OOC

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();
};
Class B
{
Public:
void show();
};
OOC

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);
OOC

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
OOC

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.
OOC

Inline Member Functions


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.
OOC

Class Distance
{ int iFeet, fInches; //private by default
Public:
void setFeet(int x)
{ iFeet =x; }
int getFeet() { return iFeet; }
Void setInches(float y) { return fInches; }
float getInches() { return fInches; }
};
OOC

//meminline.cpp
Class A
{
public:
void show();
};
Inline void A :: show() //definition in header file
{
//definition of A :: show() function
}
Inline member Functions
OOC

Constant Member Functions


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 iFeet / 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
OOC

Class Distance
{ int iFeet; float fInches;
public:
void setFeet(int);
int getFeet() const; //constant function
void setInches(float);
float getInches() const; //constant function
Distance add(Distance) const; //constant function
};
void Distance::setFeet(int x) OOC

{ 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
{ fInches=0.0; //ERROR!!
return fInches;
}
void Distance::add(Distance dd) constOOC//const function
{
Distance temp;
temp.iFeet= iFeet + dd. iFeet;
temp.setInches (fInches + dd.fInches);
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.
OOC

Mutable Data Members

Mutable data member is never constant.


1. 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
OOC

Class A //mutable.h
{
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++;//ok can modify a mutable data member in
} // const. mf
void def() //non-const. mf
{ x++; //ok can modify nonconstant data member
//in a non-const. mf
y++; //ok can modify mutable data member in a
//nonconst.mf } };
/*end of mutable.h*/
OOC

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.
OOC

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.
OOC

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.
OOC

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.
OOC

• Friend functions don’t contradict the principles of


OOPs.

• The benefits provided by data hiding are not


compromised by friend functions.
OOC

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
OOC

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
//definition of class B is after stmt declaring
//class 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
};
OOC

Class B
{ A * Aptr;
Public:

void Map(const A * const);


void test_friend( const int);
};
void B :: Map(const A*, const p);
{
Aptr=p;
}
OOC

Void B :: test_friend(int i)
{
Aptr -> x=i; //accessing private data member
}

Code effect of declaring a friend class


OOC

• 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
OOC

Class B; //friendtran.cpp
Class C;
Class A
{
friend class B;
int a;
};
Class B
{
friend class C;
};
OOC

Class C
{
void f( A *p)
{
p->a++; //error: C is not a friend of A despite
// being a friend of friend
}
};
//end of friendtran.cpp

Code to show that friendship is not transitive


OOC

Friend Member Functions


Can we make specific member functions of 1 class
friendly to another class ?
For making only ‘ B:: test_friend() ’ 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


OOC

Class A
{
/*rest of class A
Friend void B :: test_friend();
};
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 A * 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.
OOC
//Friendmemfunc.h
class A;
class B
{
A *Aptr;
Public:
void Map(const A * const);
void test_friend(const int=0);
};
class A
{
int x;
public:
friend void B :: test_friend ( const int=0)
};
Forward declaring a class that requires a friend.
OOC
Class A;
Class B
{
A *Aptr;
public:
void map(const A *A);
void test_friend(const int =0);
};
Class A
{int x;
Public: friend void B:: test_friend(const int =0);
}; inline void B:: test_friend( const p)
{
Aptr->x=p;
}
OOC

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.
OOC

Consider 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.
OOC

Objects and Functions – Objects appear as local


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
OOC
Arrays Inside Objects – An array can be declared inside the
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);
};
/*function to write the value passed as a second parameter
OOC

At position passed as first parameter*/


void A::setElement(unsigned int, int)
{ if (p<=SIZE)return; //better to throw an exception
iArray[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 iArray[p];
}
code for arrays inside the objects, always better to throw
exceptions rather than terminating the functions
OOC
Namespaces – enable C++ programmer to prevent pollution of
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
{ };
class B
{ };
Lets include both these header files in a program and see what
happens if we declare objects of the class
OOC
//multidef01.cpp
#include “A1.h”
#include “A2.h”

void main()
{ A Aobj; //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.
OOC
/*A1.h*/
namespace A1
{
class A
{ };
} /*end of namespace A1.h*/

/*A2.h*/
namespace A2
{
class A
{ };
} /*end of namespace A2.h*/
OOC
The 2 definitions of class are enveloped in 2 different
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
Qualifying the name of the class with OOC
that of the Namespace
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
OOC

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
/*longname1.cpp*/ OOC

name_space a_very_very_long_name
{ class A
{ };
}
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 { };
}
namespace x=a_very_very_long_name;
/*longname2.cpp*/ OOC

name_space a_very_very_long_name
{ class A { };
}
namespace x=a_very_very_long_name;

Void main()
{
X::A A1; //convenient short name
}
OOC
Aliases – provide an incidental benefit also. If alias name has been used at a
number of places in the 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 = N1; //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 A i.e. contained in namespace N2.
OOC

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
OOC

Here class B is defined in public section of class A.


A nested 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*/
};
/*definition of class A*/
}; A public nested class
OOC

In the listings of the 2 slides , even If there is a class 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.
Class A /*nestclassdef.h*/ OOC

{
public:
class B
{ public:
void BTest(); //prototype only
}; //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
OOC
A nested 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
};
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
OOC

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
//nestlclassobj.h OOC

Class A
{
class B
{
public:
void ATest();
};
}; //nestclassobj.cpp
#include “nestclassobj.h”
void A::ATest()
{ B1.BTest();
B B2;
B2.BTest();
} Declaring objects of nested class in the member functions of the
enclosing class
Member functions of the nested class can
OOC
access the nonstatic public
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();
};
};
OOC

//enclclassobj.cpp
#include “enclclassobj.h”

void A::B::BTest(A& ARef)


{ ARef.ATest() //ok
}
void A::B::BTest1()
{
ATest(); //Error
}
Accessing nonstatic members of the enclosing the class in
member functions of the nested class.
It can be observed that an error is produced
OOC
when a direct
Access is made to the member of the enclosing class
through the function of the nested class.

CREATION OF AN OBJECT OF A NESTED 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.

You might also like