Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
com | Website
for students | 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
1. C++ Primer, Stanley Lipmann, Josee Lajoie,
Barbara E. Moo, 4th Edition, Addison Wesley,
2005
Unit-4:
6. Inheritance
Unit-5:
7. Virtual Functions & Dynamic
Polymorphism
8. Stream Handling
Unit-6
9. Stream Handling contd 10. Operator
Overloading
Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
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
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
Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
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
Accessible by
Global Variable
any function
Accessible by Accessible by
Function A Function B
Function A Function B
Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES
Fn A Fn A Fn A Fn A
Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES
object
Data
MF
MF
Object Object
Data
Data
MF
MF
MF
MF
Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES
Corporate Paradigm
Sales Manager
Secretary
Finance
Dept
Personnel
Dept
Personnel Data
Finance Data
Personnel Manager
Finance Manager
Personnel Staff
Financial Assistant
Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES
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
Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES
Class Data1
Data2
Data3
Data
Function
Fn1
Fn2
Fn3
Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES
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
Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES
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
Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES
Eg-
void
In myfunction(int x=3,int y=4)
C, 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
Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES
Lab Program-1
• 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.
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
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.
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
}
Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES
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
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.
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
Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
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
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
But if d=28;
m=2;
y=1999;//28th Feb 1999
and we call the function as
nextday(&d1,&m1,&y1); //ok
nextday(&d1,&m2,&y2); //incorrect set passed
//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
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
OOPS Features –
1. Inheritance 2.
Polymorphism
Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES
Polymorphism
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
Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES
Eg-
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();
};
Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES
#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(); }
}
Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES
After
Struct Distance
{
int iFeet;
float fInches;
};
Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES
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);
Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
Before –
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);
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 –
Before –
void Distance :: setInches (float y)
{ fInches = y; }
After –
Void setInches(Distance * const this, float y)
{
this -> fInches = y;
}
Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES
Before –
float Distance :: getInches ()
{ return fInches; }
After –
void getInches(Distance * const this)
{
return this -> fInches;
}
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
Its evident that ‘this’ pointer should
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);
};
Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
Distance add( Distance 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
iFeet
iFeet
fInches
fInches
To
Class A
{
Public:
void show();
};
Class B
{
Public:
void show();
};
Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES
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; }
};
Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES
//meminline.cpp
Class A
{
public:
void show();
};
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
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
Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES
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
};
Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
void Distance::setFeet(int x) for students | VTU NOTES
{ 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;
}
Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
void Distance::add(Distance dd) const //const function
for students | VTU NOTES
{
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.
Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
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 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
Void B :: test_friend(int i)
{
Aptr -> x=i; //accessing private data member
}
Class B; //friendtran.cpp
Class C;
Class A
{
friend class B;
int a;
};
Class B
{
friend class C;
};
Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES
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
#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.
/*A2.h*/
namespace A2
{
class A
{ };
} /*end of namespace A2.h*/
Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES
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
Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
Qualifying the name of the class with that of the Namespace
for students | VTU NOTES
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
Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES
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;
Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
/*longname2.cpp*/ for students | VTU NOTES
name_space a_very_very_long_name
{ class A { };
}
namespace x=a_very_very_long_name;
Void main()
{
X::A A1; //convenient short name
}
Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
Aliases – provide an incidental benefit also. If alias name has been used at a
for students | VTU NOTES
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
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.
Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES
Class A /*nestpublic.h*/
{
public:
class B
{/* definition of class B*/
};
/*definition of class A*/
}; A public nested class
Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES
{
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
Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES
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
Prof. B.R.Mohan, SSE--> www.bookspar.com | Website
for students | VTU NOTES
//enclclassobj.cpp
#include “enclclassobj.h”