0% found this document useful (0 votes)
3 views101 pages

C++ Notes

The document is a comprehensive set of notes on C++ programming, covering topics such as the differences between Procedure-Oriented Programming (POP) and Object-Oriented Programming (OOP), input/output statements, class structures, inheritance, and polymorphism. It includes detailed explanations of constructors, destructors, operator overloading, and templates, along with examples of C++ programs demonstrating these concepts. Additionally, it discusses file handling, exception handling, and the structure of C++ programs.

Uploaded by

Girija Suthoju
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views101 pages

C++ Notes

The document is a comprehensive set of notes on C++ programming, covering topics such as the differences between Procedure-Oriented Programming (POP) and Object-Oriented Programming (OOP), input/output statements, class structures, inheritance, and polymorphism. It includes detailed explanations of constructors, destructors, operator overloading, and templates, along with examples of C++ programs demonstrating these concepts. Additionally, it discusses file handling, exception handling, and the structure of C++ programs.

Uploaded by

Girija Suthoju
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 101

C++Notes

UNIT-I

pop vs oops, introduction of c++: input & output statement, compiling and runningc+
+ program. pop c++ program, oops structure of c++ program, structure vs union
vsclass, scope resolution operator, inline function, class and object, access
members,explicitandimplicitmemberfunctiondeclaration,accessspecifier,staticdatame
mber and static member function, friend function & friend class, passing object
tofunction,returningobjectbyfunctionand copyingoneobjectto anotherobject.
UNIT-2

arrays of objects, pointer to object, type checking c++ pointers, this pointer, pointer
toclass member (.* and🡪*), references: independent reference, references as
functionparameters,referenceasreturnvalue,passingreferencetoobject,restrictionstorefer
ences.dynamicallocationoperatornewanddelete:initializingallocatedmemory,allocating
arrays, allocatingobject.
constructor and destructor: default constructor, parameterize constructor,
overloadedconstructor(multipleconstructorsinaclass),copyconstructor,constructorwith
defaultargument. destructor
UNIT-3
function overloading, operator overloading: restricted operator, operator
overloadingusing member function of class, unary operator overloading: ++, --. binary
operatoroverloading:+,-,*,/,%,+=,-=,*=,/=,
%=.operatoroverloadingusingfriendfunctionof class, overloading new and delete,
overloading some special operators: [ ], ( ), ->,commaoperator, <<,>>.
UNIT-4
inheritance:accessprotectedmemberofbaseclass,single,multilevel,multiple,hierarchical
and hybridinheritance (virtual base class). constructor anddestructorused in
inheritance, passing parameters to the base class constructor, granting access.run time
polymorphism: dynamic binding, pointer to derived class, virtual function,purevirtual
function, abstractbaseclass, earlyvslatebinding.
UNIT-5
the c++ input / output system basics: c++ streams, c++ predefined
streams,unformattedi/ooperations:overloadedoperators>>and<<,
get()andput()function,getline() and write() function. formatted console i/o operations,
iosformattedfunctions:.width, precision, fill, setf, ,unsetf.manipulators: setw,
setprecision, setfill,endl.creatingyourownmanipulatorfunctions

MISCELLANEOUS
Templates: class template, class template for multiple parameter types,
functiontemplate.
File handling i/o operation in c++: opening and closing file, using << and >>,
put()and get(),write() and read(), getline(), eof(), ignore(), peek(), putback(),
flush(),seekg(),seekp(), tellg()and tellp().
Exceptionhandling:

Page|1
C++Notes

UNIT-I
POP(ProcedureOrientedProgramming)
COBOL, FORTRAN and C are such programming language which
commonlycalledPOPbased languages.
Basicapproach /conceptof POP:
In this approach for any requirement, sequence of reading, calculating
andprinting instructions are grouped in a unit called procedure (function or sub
routine ormethod).For each requirement, a new procedure is created. In this way, a
singleprogram is oriented by a number of procedures. Such approach for designing
programis called POP (Procedure Oriented Programming) and programming language
thatfollowthis approach called POPlanguagelikeC.
InPOP,Datacanbeusedintwoways.
1. GlobalData:Sharableforalltheproceduresthatdeclaredoutsideofallprocedures.
2. LocalData:Accessibletothatprocedurewhereitisdeclared.Forotherprocedureloc
al dataareunknown.

Followingcontrolstructurescanbeusedineachproceduretocontrolinstructions.
1. ConditionalStructure: Toskiprunningaset ofinstructions.
2. LoopingStructure:Torunaset ofinstructionsmorethanonetimes.
DrawbacksofPOP:
1. A procedure can also use global data that does not need and affect result
ofprogram.
2. For real world application, POP becomes fail. Because large scale
programcannotbedeveloped properly.
OOPs(ObjectOrientedProgramming)
OOPs is a newapproach to designarealworldprogramand secureglobaldata.C+
+, Javaand C# areOOPsbased languages.
Basicapproach /conceptof OOPs:
Everything is considered in the form of object and they are identified on
thebasis of their properties. Objects of any class can be communicated to each
othercalledmessagepassingin OOPs.

Page|2
C++Notes
CharacteristicsofOOPs:
1. Class
2. Objects
3. Dataencapsulation
4. Dataabstractions
5. Inheritance
6. Polymorphism
7. Dynamicbinding
8. Messagepassing
AnyprogramminglanguagethatsupportallabovepropertiescalledOOPsbasedlanguagelikeC++,
Javaand C#.
1. Class:Descriptionofanyobject onthe basis of dataandfunctions
calledclass.OrUserdefined datatypeofobject called class.

2. Object: One Instance of the class is called object. Or variable of the class is
calledobject.

1. Data encapsulation: When all data of any object, are defined in a single
unitcalleddataencapsulation.Itisdoneusingmakingclass.Ex:id,length,breadth,
color and price are defined in a single unit for all objects (duster1,duster2).
2. Dataabstraction:Whenitispossibletoknowaboutany objectusingashorter name
called data abstraction. It is done by defining the class name. Ex:Dusteris
anameofclassthat definesabout duster1 andduster2.
3. Inheritance: When a new class (derived class) is enabled to access
propertiesofold class (baseclass)called inheritance.

Page|3
C++Notes
InthisexamplestationaryisacommonclassforDusterandMarkerclass.Both classes
do not to redefine id, color and price data types. They are
linkedusinginheritance.
4. Polymorphism:Iftwoormorefunctionshavingsamenamethenitiscalledpolymorp
hism.
5. Dynamicbinding:Whenitispossibletolinkafunctiontoitsfunctioncallatruntimeth
en it is calleddynamicbinding.
6. Messagepassing:Objectsofanyclasscanpassdatatoeachothercalledmessagepassi
ng.
AdvantagesofOOPs:
1. DataHiding:Privatedataoftheclasscan’tbeaccessedfromoutside.
2. Security of data: Data of the class can be accessed as a private, protected
andpublic.Privateforsameclass,protectedforderivedtooandpublicforanywhere.
3. Reusability:Usinginheritance,membersofoldclasscanbeusedintonewclass.
4. Easydevelopment:Largesizeofrealworldapplicationcanbeeasilydeveloped.
5. Easytodebug:Allclassescanbedebuggedseparately.
Uses/ApplicationofOOPs:
Nowadays OOP is muchpopularbecausewecanusetheirconceptto
solveinanytypeofproblems someofthem aremuch like:
1. Realtimesystem
2. Simulationandmodeling
3. Objectorienteddatabase
4. Hypertextandhypermedia
5. AIand expertsystem
6. Decisionsupportandofficeautomation
7. CAM/CADSystem

Page|4
C++Notes

IntroductionofC++:
- C++isanobject-oriented programminglanguage.
- It was developed by Bjarne Stroustrup at AT&T Bell Laboratories in
MurrayHill,NewJersey,USA, in theearly1980’s.
- C++ is an extension of C therefore initially it was called ‘C with
classes’.In1983,thenamewaschangedtoC+
+duetoideacomesfromtheCincrementoperator++.
- C++isasupersetofC. AlmostallcprogramsarealsoC++programs.
- C++atrulyobject-orientedlanguagebecauseitprovidesthefacilitiesofmakingclass,
objects, inheritanceandpolymorphism.
Input(cin)&Output(cout)statementinC++:
Inc++,iostream.hheader file isusedtosupportallinputoutputstreamsclassesinourprogram.
Outputstatement:using“cout<<”streamobjectwecandisplaydataonmonitor.
(justlikeprintfin c)
Inputstatement:using“cin>>”streamobjectwecanassignkeyboardvaluetothevariableof
theprogram.(just likescanfin c)
Example:u1p1.cpp
#include<iostream.h>
voidmain()
{
inta;
cout<<"\n Input
Integer:";cin>>a;
cout<<"\nIntegervalueis"<<a;
}
Output:
Input Integer:
11Integervalueis11
If numberofdataaremorethan eachdatamustbeseparated by<<or>>.
cout<< "a =" << a << "\
n";willdisplayonmonitoras-

a=11cin>>a>>b;
Thisstatementreadstwovaluesfromkeyboardandstoretofirstinvariableathento
variableb.
CompilingandrunningC++program:
1. InstallTurboC++softwareinDOS basedoperatingsystem.
2. OpenTC.exefilefromlocationc:\TC3orTC\BIN\TC.exe.
3. TypeC++programandsave.
4. CompileusingAlt+F9.
5. IfprogramiserrorfreethenrunusingCtrl+F9.
6. CheckoutputscreenusingAlt+F5.

Page|5
C++Notes

POP(ProcedureOrientedProgramming)C++Program:

Program:u1p2.cpp
//Documentation
/*
ProgramtodemonstratePOPorganizationandToptoDownapp
roach, Created by:www.LRsir.net
*/
//includefiles
#include<iostream.h>
//Globaldeclaration
inta,b;
void
getdata(int,int);voids
howdata();
intsum();
//Mainfunction
voidmain()
{
getdata(10,20);
showdata();
int
c=sum();cout<<"\
nSum="<<c;
}
//Userdefinedfunctions
voidgetdata(intp1,intp2)
{
a=p1;
b=p2;
}
voidshowdata()
{
cout<<"\n"<<a<<"\t"<<b;
}
intsum()
{
returna+b;
}
Output:
a=10 b=20
Sum=30
Remark:
/*……*/ismultilinecomment
//…..issinglelinecomment
Variables can be declared anywhere before use in C+

Page|6
C++Notes
+.InC++,programcanbedesignedinPOPorOOPsstyle.

Page|7
C++Notes

OOPsStructureofC++Program:(Bottom-upApproach)
ThestructureofC++program canhavefoursections.

1. Documentation: In this section we write comment about program that ignore


bycompiler. In comments we can write program name, uses, developer name,
date,anyhelpetc.Commentsarewrittenin/*--------*/(multilinecomment)and//------
(singlelinecomment).
//Documentation
/
*ProgramtodemonstratePOPorganizationandToptoDownappro
ach, Created by:www.LRsir.net */
2. Include file section: In this section all needful files are included in the
programthatcontains declarationofclassand functionsused intheprogram.
Ex: #include<iostream.h>
Containdeclarationofcoutandcinstreamobject.
3. Class declaration section: In this section we create classes. Every class
containsdataandfunctiondeclaration.Inclasswecanalsodefinememberfunctions.
Ex:
classA
{
int
a,b;publ
ic:
void
getdata(int);void
showdata();intsum(
);
};
4. Member function definition: In this section, all explicit member functions of
theclassaredefinedoutsidetheclassusingscoperesolution operator(::).
Ex:
voidA::getdata(intp1,intp2)
{
a=p1;
b=p2;
}
voidA::showdata()
{

Page|8
C++Notes
cout<<"\n"<<a<<"\t"<<b;
}

Page|9
C++Notes

intA::sum()
{
returna+b;
}
5. Main function section: In this section we can declare object of class and
callpublicmemberfunctionsoftheclass.
Ex:
voidmain()
{
A
ob;ob.getdata(1
0);ob.showdata(
);intc=ob.sum()
;
cout<<"\nSum="<<c;
}
InthiswayaOOPsC++ programisdesignedinfoursections.
OOPs(ObjectOriented Programmings)C++Program:
Onthebasisofabovestructure, anOOP’sC++willdesign infollowingorder.
Program:u1p3.cpp
//Documentation
/*ProgramtodemonstrateOOPsorganizationandBottom-
Upapproach,Created by:www.LRsir.net
*/
//includefiles
#include<iostream.h>
//classdeclaration
classA
{
inta,b;p
ublic:
voidgetdata(int);v
oid
showdata();intsum(
);
};
//Memberfunctiondefinition
voidA::getdata(intp1,intp2)
{
a=p1;
b=p2;
}
voidA::showdata()
{
cout<<"\n"<<a<<"\t"<<b;
}
intA::sum()
{
returna+b;

Page|10
C++Notes
}

Page|11
C++Notes
//Mainfunction
voidmain()
{
A
ob;ob.getdata(1
0);ob.showdata(
);intc=ob.sum()
;
cout<<"\nSum="<<c;
}
Output:
a=10 b=20
Sum=30
StructurevsUnionvsClass
Structure Union Class
Structurebodysupports Union bodysupports only Classbodysupportsdata members
onlydatamembers. datamembers. aswellasmember functions.
All data members Only one largest size Alldatamembersarecreatedwhen
arecreated when ofdata member is variableofclass(object)iscreated.
variableofstructureisc createdwhenvariableofun
reated. ionis
created.
Bydefault,structure Bydefault, union Bydefault,classmembersare
membersarepublic. membersarepublic. private.
structkeywordisused unionkeywordisusedto classkeywordisusedtodefine
todefinestructure. defineunion. class.
Ex:Program:u1p4. Ex:Program:u1p5. Ex:Program:u1p6.cpp
cppstructA cppunionA classA
{ { {
int int int
a;intb a;intb a;int
; ; b;publi
}; }; c:
voidmain() voidmain() voidget(intp1,intp2)
{ { {
A A a=p1;
oa;oa.a= oa;oa.a= b=p2;
10;oa.b= 10;oa.b= }
20; 20; voidshow()
out<<oa.a<<"\ cout<<oa.a<<"\ {
n"cout<<oa.b; n"cout<<oa.b; cout<<oa.a<<"\
} } n"cout<<oa.b;
Output: Output: }
10 20 };
20 20 voidmain()
{
A
oa;oa.get(10,2
0);
oa.show();
}

Page|12
C++Notes
Output:
10
20

Page|13
C++Notes

ScopeResolutionoperator(::)
If a function that uses same name of global variable and local variable then by
localvariable will be accessed. But if we want to use global variable then use
scoperesolutionoperator(::)with variablename.
Example:Program:u1p7.cpp
#include<iostream.h>
intn=10; //global
variablevoidmain()
{
intn=20;//localvariable
cout<<"\n Access local variable:"<< n;cout<<"\
nAccessglobalvariable:"<<::n;
}
Output:
Access local variable:
10Accessglobalvariable:20
In this program, name of local and global variable having the same name (n)
thereforeinside any function n will be consider as local variable and ::n will be
consider asglobalvariable.
Inlinefunction:
Afunctionthatcontainonlyoneortwolineofcodeanddefineusinginline
keywordcalledinlinefunction.
Syntax:
inlinefun_name(typearg1,typearg2,…)
{
One/twolineof code
}
Example:Program:u1p8.cpp
#include<iostream.h>
inlineintaddition(int a,int b)
{
returna+b;
}
voidshow(intn)
{
cout<<n;
}
voidmain()
{
intx;
x=
addition(10,20);sho
} w(x);
Output:
30
Inthisexampleaddition()isaninlinefunctionwhereasshow()isnot.

Page|14
C++Notes
Benefitof inlinefunction:
At compile time, function calling statement is replaced by codes of inline
functionthat save time consuming to jump on that function at run time. If inline
function hasloop or a number of statement then inline function behave normal
function. Memberfunctions that define inside the class and having only one or two
line of code alsocalledinlinefunction.
What is class and object? How class is defined using data
memberandfunction?Howobjectaccessmembersoftheclass?
Classdeclaration:
Adescriptionofanyobject iscalledclass.Datamembers
andfunctionsoftheobjectcanbedefined insidetheclass body.
Syntax oftheclass:
classcls_name
{
Data Member’s
Declarationpublic:
MemberFunction’sDefinitions
};

Data members of the class can be accessed only by member functions of the
sameclass.
Member functions will be called by objects as per
needs.Ex:
classDuster
{
intid;
int
length;intbr
eadth;
char
color[10];float
price;
public:
voidgetdata()
{
cout<<"\
nInputid,length,breadthofduster:”;cin>>id>>le
ngth>>breadth;
cout<<”Input color and price of
duster:";cin>>color>>price;
}
voidshowdata()
{
cout<<"\nDuster record
is:";cout<<"\
nId="<<id;cout<<"\
nlength="<<length;cout<<"\
nbreadth="<<breadth;cout<<"\

Page|15
C++Notes
ncolor="<<color;cout<<"\
nprice="<<price;
}
};

Page|16
C++Notes

In this example id, length, breadth, color and price are data members and used
bygetdata() and showdata() member functions. They are related to any Duster objects
sosuitablenameoftheclass is Duster.
Objectdeclaration:
Instances of class or variable of class data type is called object. When object is
createdthendatamembers oftheclass is created.
Syntax:
cls_nameobj_name1,obj_name2;
Example:
voidmain()
{
Dusterduster1,duster2;

Whenmorethanobjectsaredeclaredthenseparatedatamembersarecreatedforeachobject.
Accessing membersoftheclass:
Objectoftheclasscanaccesspublicmembersusing.
(dot)calledperiodormembershipoperator.
Syntax:
obj_name1.member_name
obj_name2.member_name
Example:
voidmain()
{
Duster duster1,
duster2;duster1.getdata(
);duster2.getdata();dust
er1.showdata();duster2.s
howdata();
}
If duster1 call getdata() and showdata() member function then, these function
accessdata of object duster1, similarly if duster2 object call these member function
then theyaccessdataofduster2.

Page|17
C++Notes
Program:u1p9.cpp
//
programtodemonstrateoopsbaseddusterinformation#include
<iostream.h>
classDuster
{
intid;
int
length;intbr
eadth;
char
color[10];float
price;
public:
voidgetdata()
{
cout<<"\
nInputid,length,breadthofduster:”;cin>>id>>le
ngth>>breadth;
cout<<”Input color and price of
duster:";cin>>color>>price;
}
voidshowdata()
{
cout<<"\nDuster record
is:";cout<<"\
nId="<<id;cout<<"\
nlength="<<length;cout<<"\
nbreadth="<<breadth;cout<<"\
ncolor="<<color;cout<<"\
nprice="<<price;
}
};
voidmain()
{
Duster duster1,
duster2;duster1.getdata(
);duster2.getdata();dust
er1.showdata();duster2.s
howdata();
}
Output:
Inputid,length,breadthofduster:101 10

20(enter)Inputcolorand priceof duster:Red 25(enter)

Dusterrecordis:";
Id=101
length=10b
readth=20c
olor=Redpr

Page|18
C++Notes
ice=25;

Page|19
C++Notes

ExplicitandImplicitmemberfunctiondeclaration:
Therearetwowaystodeclarememberfunctionof theclass.
1. Implicitly: When member function is defined inside the class body
calledimplicitfunction declaration.
2. Explicitly: When member function is defined outside the class body
usingscope resolution operator(::) called explicit member function declaration.
Thiswayimprovetheclarityoftheclass body.
Example:Program:u1p10.cpp
//
programtodemonstrateoopsbaseddusterinformation#include
<iostream.h>
classDuster
{
intid;
int
length;intbr
eadth;
char
color[10];float
price;public:
//defineinsideclassbody-
implicitfunctionvoidgetdata()
{
cout<<"\
nInputid,length,breadthofduster:”;cin>>id>>le
ngth>>breadth;
cout<<”Input color and price of
duster:";cin>>color>>price;
}
//defineoutsideclassbody-
explicitfunctionvoidshowdata();
};
//explicit function of Duster
classvoidDuster::showdata()
{
cout<<"\nDuster record
is:";cout<<"\
nId="<<id;cout<<"\
nlength="<<length;cout<<"\
nbreadth="<<breadth;cout<<"\
ncolor="<<color;cout<<"\
nprice="<<price;
}
//Main
functionvoidmai
n()
{
Duster duster1,
duster2;duster1.getdata(
);duster2.getdata();dust

Page|20
C++Notes
er1.showdata();duster2.s
howdata();
}
Output:sameas previous

Page|21
C++Notes
In this class getdata() and showdata() both are member functions of Duster class,
butgetdata() is defined inside class body wheareasshowdata() is defined outside the
classbody using :: operator. Before defining explicit function, it must be declared in
classbody.
Access specifier /modifier of the
class(Visibilitymode/label)
InC++,everydatamembersandmemberfunctionsaredeclaredinfollowingtypeofsections.
1. private
2. public
3. protected
Theyareusedas
classcls_name
{
private:
members(data+function)
protected:
members(data+function)
public:
members(data+function)
};
Orderofsectioncanbechanged.Onelabelscanberepeated.
Usesof label:
1. private:membersofprivatesectionsareaccessibleonlybymemberfunctionsofsame
class,friend functionsofthat classand itsfriend class.
2. public:membersofpublicsectionsareaccessibleonlybymemberfunctionsofsamec
lassaswellasallnonmemberfunctionsthroughoutintheprogram.
3. protected:membersofprotectedsectionsareaccessibleonlybymemberfunctionsof
sameclassas wellas memberfunctions ofderivedclass.
Example:Program:u1p11.cpp
//
programtodemonstrateprivate,protectedandpublic#includ
e<iostream.h>
classA
{
private:
int
a;protected
:
int
b;public:
intc;
//memberfunctions
voidgetdata(intp1,intp2)
{
a=p1;
b=p2;
}

Page|22
C++Notes

voidshowdata()
{
cout<<"\na="<<"\tb="<<b;
}
};
voidmain()
{
Aob;
//ob.a=10;not accessibledue toprivate
//ob.b=20;not accessible due to
protectedob.c=30;//Accessible due to
publicob.getdata(10,20);//Accessibleduetopubl
icob.showdata(); //Accessible due to
publiccout<<"\nc="<<c;//Accessibledueto
public
}
Output:
a=10
b=20
c=30
Foroneclass,protectedmembersbehavesasprivate.Innormalpractice,datamembers are
kept in private section and member functions in public section. In
theabsenceoftheselabels, uppermemberswill beconsideringprivate.
Staticdatamember andstaticmemberfunction:
Static data member of the class is common for all objects of that class. That is
staticdatais createdonlyonetimes forobjects.Defaultvalueofstaticdatamemberis0.
Static member function of the class can access only static data member of that
classand it can bedirectlybyclass name.
statickeywordisusedtodefinestaticdatamemberandstaticmember function.
Example:
Program:u1p12.cpp#in
clude<iostream.h>cla
ssA
{
static int
n;public:
staticvoidcounter()
{
n++;
cout<<"\n"<<n;
}
};
int
A::n;voidma
in()
{
1
2
}
Output:

Page|23
C++Notes
A::cou
nter()
;
A::cou
nter()
;

Page|24
C++Notes
Inthisprogramnisa static data member whereascounter() isa static memberfunction that
use static data n to count number of function calling. Class A can
calldirectlystaticfunction counter()using:: operator.
FriendFunction&Friendclass:
By default,alldata membersof the classare private andonly
usablebymemberfunction ofthatclass.
FriendFunction:
A function which is not a member of the class but capable to use private data of
thatclasscalledfriendfunction. In c++friend functionisdeclaredusingfriend keyword.
Example:Program:u1p13.cpp
#include<iostream.h>
classA
{
int a,
b;public:
intlarger()
{
return(a>b ?a:b);
}
friendvoidfun();
};
voidfun(intp1,int p2)//friendfunctionof classA
{
A
ob;ob.a=
p1;ob.b=
p2;
intn= ob.larger();
cout<<"\nLargenumber is"<< n;
}
voidmain()
{
larger(10,20);
}
Output:
LargeNumber is20
In this program fun() is not a member function of class A but it is using private data
inthe form of ob.a&ob.b. Normally it is invalid to use but no error because fun()
ispubliclydeclared usingfriend keyword insidetheclass A.
Friendclass:
Let A and B are two classes and if class B is capable to use all private data of class
AthenclassBwillbecalledfriendclassofA.Friendclassisdeclaredusingfriendclass.
Example:Program:u1p14.cpp
#include<iostream.h>
classB;

Page|25
C++Notes

classA
{
int a,
b;;public:
intlarger()
{
return(a>b ?a:b);
}
friendclassB;
};
ClassB
{
public:
voidfun(int p1,int p2)
{
Aob;
ob.a=p1;//class B uses private data of
Aob.b=p2;
intn= ob.larger();
cout<<"\nLargenumber is"<< n;
}
};
voidmain()
{
B
obj;obj.fun(10,
20);
}
Output:
LargeNumber is20
InthisprogramclassBisthefriendclassofclassA,thereforeanyfunctionofclassBcanuses
privatedataofclass A.
Passingobjecttofunction,returningobjectbyfunctionandcopyingoneobj
ectto anotherobject:
Passingobject:

Wecanpassobjecttothefunctioninthesamewayaswepassintegerdatabutargumentsofthatf
unction must bedefinewithclass typeofpassingobjects.

Returningobject:

Anyfunctioncanalsoreturnoneobjectinthesameway
aswereturnoneintegerdatabutfunction typemust bedefinedwith class
typeofreturningobject.

Copyingobject:

All data of one object can be copied into another object using single
assignmentoperator (=) in the same way as we copy integer value to integer variable,
but classtypeofboth object must besimilar.

Page|26
C++Notes

Example:Program:u1p15.cpp

#include<iostream.h>
classcomplex
{
inta,b;pu
blic:
voidgetdata(intp1, intp2)
{
a=p1;
b=p2;
}
voidshowdata()
{
cout<<"\n"<<a<<"+"<<b<<"i";
}
friendcomplexsum(complex,complex);
};

complexsum(complexc1,complex c2)
{
complex
c3;c3.a=c1.a+c2
.a;c3.b=c1.b+c2
.b;returnc3;
}

voidmain()
{
complex
oc1,oc2,oc3;oc1.getdata(2,3); /
/to input 2+3ioc2.getdata(4,5);
//to input
4+5ioc3=sum(oc1,oc2);
oc3.showdata(); //we get 6+8i
}
Output:
6+8i
In this example complex is a class to define any complex in the form of (a+bi).
Heresum() is a friend function of complex class in which we pass two objects oc1 and
oc2.After addition this function returns an object c3 of complex type. Using = we
canassignreturningobject tooc3 object.

Page|27
C++Notes

Unit-2
Arraysofobjects:
In C++ it is possible to create array of objects of same class type. If we want to
workonanumberofobjectsofsameclassthenarraysofobjectsarebetteroptioninplaceofdecl
aringobjects separatelyin thesamewayaswecreatearrayofanyothertype.
Example:Program:u2p1.cpp
#include<iostream.h>
classA
{
int
a,b;publ
ic:
voidgetdata()
{
cout<<"\n Input any two integer
values:";cin>>a;
cin>>b;
}
voidshowdata()
{
cout<<"\
na="<<a;cout<<"\
tb="<<b;
}
};
voidmain()
{
A ob[5]; //arrays of 5
objectsfor(inti=0;i<5;i++)
Ob[i].showdata();cout<<"\nData
of all objects are:";for(i=0;i<5;i+
+)
Ob[i].showdata();
}
Output:
Inputanytwo integervalues:10

20(enter)Inputanytwo integervalues:30

40(enter)Inputanytwo integervalues:50

60(enter)Inputanytwo integervalues:70

80(enter)Inputanytwo integervalues:90

100(enter)Dataof all objects are:


a=10
b=20a=30
b=40a=50

Page|28
C++Notes
b=60a=70
b=80a=90b=
100
In this example, ob[5] is arrays of 5 objects of same class A type. Each object
canaccess their members using ob[i].getdata() or ob[i].showdata(). Here I denote
index ofarraythat varyfrom 0 to 4.

Page|29
C++Notes

Pointertoobject:
Addressofobjectcanbeholdintopointerofsametypeofclass.Inthiscase,pointertoobjectcan
alsoaccessmembersofobjectusing🡪(arrow)referenceoperator.
Example:Program:u2p2.cpp#i
nclude<iostream.h>cl
assA
{
int
a,b;publ
ic:
voidgetdata()
{
cout<<"\n Input any two integer
values:";cin>>a;
cin>>b;
}
voidshowdata()
{
cout<<"\
na="<<a;cout<<"\
tb="<<b;
}
};
voidmain()
{
A*p; //pointer to
objectAob; //object
p=&ob; //hold
addressp🡪getdata();p🡪sho
wdata();ob.showdata();
}
Output:
Inputany twointeger values:10

20(enter)a=10b=20 (by pointer to object)


a=10b=20(by object)

Inthisexample,pispointertoobjectob.Thereforepointerpcanalsoaccessmembersofobject
ob.
TypecheckingC++pointers:
InC++,wemustbesametypeofpointerwhileassigningonepointerintoanotherpointer.C+
+compilerchecks sametypeofpointer.
Forexample:
int
*pi;float*
pf;
inC++,thefollowingassignmentisillegal:
pi= pf;// error --type mismatch
C++'s stronger type checking where pointers are involved differs from C, in
whichyou mayassignanyvalueto anypointer.

Page|30
C++Notes

thispointer:
When an object is called member function then pointer to this object also
passedautomaticinternally,calledthispointer.Insidememberfunctionthiskeywordreprese
ntpointerofcallingobject and *this representcallingobject.
Example:
Program:u2p3.cpp#inc
lude<iostream.h>clas
sA
{
int
a,b;publ
ic:
Agetdata()
{
cout<<"\n Input any two integer
values:";cin>>a;
cin>>b;return
*this;
}
voidshowdata()
{
cout<<"\
na="<<a;cout<<"\
tb="<<b;
}
};
voidmain()
{
A
ob1,ob2;ob2=ob1.getdata
(10,20);ob1.showdata();
ob2.showdata();
}
Output:
a=10 b=20 (values of
ob1)a=10b=20(valuesofob2)
getdata()memberfunctionreturn*thisanditisanobjectob1insidememberfunction.
Pointertoclassmember(.*and🡪*)
Offsetsofpublicmemberscanbe assignedtopointervariableofclassmember,thenthey
canbeaccessedby objectusing(.*)operatororpointertoobject(🡪*).
Example:Program:u2p4.cpp
#include<iostream.h>
classA
{
public:
inta;
voidshow()
{
cout<<"\nwww.LRsir.net:"<<a;

Page|31
C++Notes
}
};

Page|32
C++Notes

voidmain()
{
intA::*data;//pointerto datamember
void(A::*fun)()//
pointertomemberfunctiondata=&A::a;
//assign offset of
afun=&A::show;//assignoffset ofshow()
Aob; //object
A*p; //pointer toobject
p=&ob; //assignaddress ofob top

ob.*data=10; //
ob.a=10;ob.*fun();

//ob.show();p🡪*data=20;

//ob.a=20;p🡪*fun();//ob.sho
w();
}
Output:
www.LRsir.net:10
www.LRsir.net:20
Heredataispointertoclassdatamemberthatcanholdoffsetofintegerdatamembera and fun()
is pointer to class member function that can hold offset of show()
likememberfunction.obisobjectofAwhereaspisitspointer.Therefore“.*”isapplicable
withoband“🡪*” withpointer toob.
References:
Areferenceisimplicitpointer.Itisdeclaredusing&operator.Atthetimeofdeclaration,
variable or object can be assign or passes then reference becomes alias,therefore we
can use reference in place actual variable. It can be used in followingways.
1. Independentreference
2. Referencesasparameters
3. Returningreference
4. Passingreferencetoobject
Independentreference):Whenavariableisassignatthetimeofreferencedeclarationthen
referencebecomesalias ofvariable.
Example:Program:u2p5.cpp
#include<iostream.h>
voidmain()
{
inta;int
&r=a;r=10
;
cout<<"\n"<<a;
}
Output:
10
Here risstandalonereferenceofaor aliasofa,thereforerpointtoa.

Page|33
C++Notes
Referencesasfunctionparameters:
Whenparametersoffunctionsarereferencesthentheybecomealiasofpassingvalues.Iffunct
ionmodifiesreferencesthenthischangetakesonactualvalues.
Example:Program:u2p6.cppswapping twonumber
#include<iostream.h>
voidswap(int &x,int &y)
{
int
t;t=x;
x=y;y=
t;
}
voidmain()
{
inta=10,b=20;s
wap(a,b);
cout<<"\na="<<a<<"\tb="<<b;
}
Output:
a=20b=10
Inthisexample,xandyarereferenceparametersthatcanholdreferenceofaandbrespectively.
Referenceasreturnvalue:
Referencecan also return fromanyfunction.
Example:Program:u2p7.cppReplaceRbysmall r.
#include<iostream.h>
char
s[15]="www.LRsir.net"char&
replace(int i)
{
returns[i];
}
voidmain()
{
replace(5)='r';
cout<<s;
}
Output:
www.Lrsir.net
"char&replace(inti)"returnreferenceof givenindexingcharacterthatreplacebyr.
Passingreferencetoobject
Wecanalsopassreferenceofanyobjecttothefunction.Iffunctionchangeusingreferencethenit
ismadeonactual object,becausenocopyismadeofpassingobject.
Example:Program:u2p8.cpp

Page|34
C++Notes
#include<iostream.h>
classA
{
int a,
b;public:
voidgetdata(intp1, intp2)
{
a=p1;b=p2
;
}
voidshowdata()
{
cout<<"\
na="<<a;cout<<"\
tb="<<b;
}
friendvoidsign(A &);
};
voidsign(A&or)
{
or.a=(-or.a);
or.b=(-or.b);
}
voidmain()
{
A
ob;ob.getdata(10,-
20);sign(ob);ob.sho
wdata();
}
Output:
a=-10 b=20
Itisclearthatreference(or)isaliasofpassingobject.Thereforesignchangesondatamembersofpassin
gobject ob.
RestrictionstoReferences
- Areferencevariablemustbeinitializedwhenitisdeclared.
- Nullreferencesareprohibited.
- Wecannotreferenceanotherreference.
- Wecannotobtaintheaddressofa reference.
- Wecannotcreatearrays ofreferences.
- Wecannotcreateapointerto areference.
Dynamicallocationoperator:(newanddelete)
At run time we can allocate required amount of memory space using new
operator(mallocinc)andreleasedusingdeleteoperator(freeinc).Atruntimewec
an allocateand releasesmemoryspacefor:
1. Onedata allocationwithinitialvalue
2. Allocatingarray
3. Allocatingobject

Page|35
C++Notes

newoperatorgivesabaseaddressofallocatedmemoryspaceotherwiseNULL,that
assign tothepointervariable.
deleteoperatorreleased memoryspaceofpassing pointer.
InitializingAllocatedMemory
Assign a value at the time of memory
allocation.Syntax:
ptr= newtype (value);
Example:Program:u2p9.cpp
#include<iostream.h>
voidmain()
{
int*p;
p = new int(10); // initialize to
10cout<<"\nAddress="<<p;cout<<"\
tvalue="<<*p;
deletep;
}
Output:
Address=65677value=10

Here p is pointer to integer that holds new allocated address of integer and
initializeby10. Afterend need it is removed usingdelete.
AllocatingArrays
Wecan createdynamicarraybyallocating arraysusingnewoperator.
syntax:
p=new array_type[size];
Here,sizeismaximumlimitofarray.
Tofree anarray,usethisformofdelete:
delete[ ] p;
Example:Program:u2p10.cpp
#include<iostream.h>
voidmain()
{
int*p, n i;
cout<<"\nInput array
size:";cin>>size;
p=new int[n]; // allocateinteger
arraycout<<"Inputdata:";
for(i=0; i<n; i+
+ )cin>>p[i];
cout<<"\nArray
data:"for(i=0;i<n; i+
+)
cout<<"\t"<<p[i];

Page|36
C++Notes

delete[] p;// releasethe array


}
Output:
Inputarraysize:3
Inputdata: 1020 30(Enter)
Arraydata: 1020 30
Here“p=newint[n];”allocatearrayatruntimeandafterused“delete[]
p;”releasedarrayspace.
Allocatingobject
Wecanalsocreateobjectatruntimeusingnewoperator.
syntax:
p= newclass_type;
Tofreeobject:
deletep;
Example:Program:u2p11.cpp
#include<iostream.h>
classA
{
public:
A()
{
cout<<"\nObjectcreated";
}
~A()
{
cout<<"\nObjectremoved";
}
voidshow()
{
cout<<"\nwww.LRsir.net";
}

};
voidmain()
{
A
*p;p=new
A;p🡪show(
);deletep
} ;
Output:
Objectcreatedw
ww.LRsir.netob
jectremoved
here🡪(arrow)operatorisusedtoaccessmembersbypointertoobject.

Page|37
C++Notes

Constructoranddestructor:
Meaning of constructor: At runtime constructor creates objects of the class.
Whenobject is creating, all data members of its class are also creates in the memory.
We
canexecutecodesofspecifiedfunctionautomaticallyduringobjectcreation,suchfunctionca
lled constructorfunction.
Featuresof constructor functionin C++:
1. Thenameof constructorfunctionissimilartotheclassname.
2. Itdoes not specifyanyfunction type.(even not void)
3. Italwaysdefinesinpublicsection.
4. Itcanbedefaultorparameterized.
5. Morethanoneconstructorfunctionscanbedefinedinoneclassi.e.canbeoverloads.
GeneralSyntaxofconstructor:
classcls_name
{
Datamembersection
public:
//default
constructorcls_name()
{

}
// parameterized
constructorcls_name(typepar1,typepar2,
….)
{

}
};
Typeof constructorfunction:
Onthebasisofparametersdefinedinconstructorfunction,itcanbeclassifiedintofollowingcategories
.
1. Defaultconstructor
2. Parameterizeconstructor
3. Overloadedconstructor(multipleconstructorsinaclass)
4. Copyconstructor
5. Constructorwithdefault argument
1. Default constructor: A constructor function that does not specified any
parametersandused to initializedefaultvalues ofobject’s datamember.
Example:Program:u2p12.cpp
#include<iostream.h>
classA
{
int
a,b;publ
ic:

Page|38
C++Notes
//defaultconstructor

Page|39
C++Notes

A()
{
a=10;
b=20;
}
voidshowdata()
{
cout<<"\n"<<a<<"\t"<<b;
}
};
voidmain()
{
A
ob1,ob2;Ob1.sho
wdata();Ob2.sho
wdata();
}
Output:
10 20
10 20
In this program A() is a default constructor that invoked automatically when object
ofclassAisdeclaredwithoutpassingvalues.ForeachobjectofA,itsdefaultconstructorwill
set10 & 20to thedatamembersa&b respectively.
2. Parameterized constructor: A constructor that specified one or more
parametersandusedtoinitializeobject’sdatamemberby passing valuesalong
withobjectdeclaration.
Example:Program:u2p13.cpp
#include<iostream.h>
classA
{
int
a,b;publ
ic:
// parameterized
constructorA(intp1,int p2)
{
a=p1;
b=p2;
}
voidshowdata()
{
cout<<"\n"<<a<<"\t"<<b;
}
};
voidmain()
{
Aob1(10,20),ob2(11,22);
Ob1.showdata();
Ob2.showdata();
}

Page|40
C++Notes
Output:

Page|41
C++Notes

10 20
11 22
InthisprogramA(intp1,intp2)isaparameterizedconstructorthatinvokedautomatically
when object of class A is declared with two integer values. These twovalueswill
bestoreto thedatamembers ofobject.
3. Overloaded constructor: When more than one constructor is defined in a
class,then such constructors are called overloaded constructor. Every constructor must
bedistincton thebasis ofparameters.
Example:Program:u2p14.cpp
#include<iostream.h>
classA
{
int
a,b;publ
ic:
// default
constructorA()
{
a=10;
b=20;
}
// constructor with one
parameterA(intp1)
{
a=p1;
b=22;
}
// constructor with two
parametersA(intp1,int p2)
{
a=p1;
b=p2;
}
voidshowdata()
{
cout<<"\n"<<a<<"\t"<<b;
}
};
voidmain()
{
Aob1,ob2(11),ob2(5,7);
Ob1.showdata();
Ob2.showdata();
ob3.showdata();
}
Output:
10 20
11 22
5 7

Page|42
C++Notes
Inthisprogram,threeconstructorsaredefinedwithdifferentnumberofparameters.Objectob
1invokedA(),ob2(11)invokedA(int) andob3(5,7)invokedA(int,int).
4. Copyconstructor:Aconstructorthatiscapabletocopyoldobjectintonewobjectatthetim
eofobject creation.
Example:Program:u2p15.cpp
#include<iostream.h>
classA
{
int
a,b;publ
ic:
// copy
constructorA(A&ob)
{
a=ob.a;
b=ob.b;
}

// constructor with two


parametersA(intp1,int p2)
{
a=p1;
b=p2;
}
voidshowdata()
{
cout<<"\n"<<a<<"\t"<<b;
}
};
voidmain()
{
Aob1(10,20);
A ob2=ob1; // or A
ob2(ob1);Ob1.showdata();Ob2.
showdata();
}
Output:
10 20
10 20
Inthisprogram, A(A&oc)isacopyconstructorthatcan copyobject ob1into ob2.
5. Constructor with default argument: A constructor that defines parameter
withdefault values called constructor with default arguments. is capable to copy old
objectintonewobject at thetimeofobject creation.
Example:Program:u2p16.cpp
#include<iostream.h>
classA
{
inta,b;

Page|43
C++Notes

public:
// constructor with default
argumentsA(intp1=0,int p2=0)
{
a=p1;
b=p2;
}
voidshowdata()
{
cout<<"\n"<<a<<"\t"<<b;
}
};
voidmain()
{
Aob1,ob2(11),ob3(5,7);
ob1.showdata();
ob2.showdata();
ob3.showdata();
}
Output:
0 0
11 0
5 7
In this program, A(int p1=0, int p2=0) is constructor with default argument and
itinvokedforob1 orforob2(11)orforob3(5,7).
Meaningof
destructor:Atruntimedestructorremovesunusedobjectfrommemory.Whenobjectisre
moving,alldatamembersarealsoremove.Wecanexecutecodesofspecifiedfunctionautoma
ticallyduringobjectremoval,suchfunctioncalled destructorfunction.
Featuresof destructorfunction in C++:
1. Thenameofdestructor functionissimilartotheclassnamewithprefix~sign.
2. Itdoesnot specifyanyfunction type.(notevenvoid)
3. Italwaysdefinesinpublicsection.
4. Ithasnoparameters.
5. Destructorneveroverloads.
GeneralSyntaxofconstructor:
classcls_name
{
Datamembersection
public:
//destructor
~cls_name()
{


}
};
Example:Program:u2p17.cpp

Page|44
C++Notes
#include<iostream.h>
classA
{
int
a,b;publ
ic:
//
constructorA()
{
a=10;
b=20;
cout<<"\nObjectcreated";
}
//destructor
~A()
{
cout<<"\nObjectremoved";
}
voidshowdata()
{
cout<<"\n"<<a<<"\t"<<b;
}
};
voidmain()
{
A
ob1;Ob1.showdat
a();
}
Output:
10 20
Object
createdObjectr
emoved
InthisprogramA()isaconstructorthatinvokedwhenobjectiscreatedwhereas~A()isdestruct
orthatinvokedwhen objectis removefrommemory.

Page|45
C++Notes

Unit-3
Functionoverloading:
Function overloading is one example of compile time polymorphism.
Whenmore than one function are defined with the same name but mismatch on the
basis ofparameters then such functions are called overloaded function and this
mechanismcalledfunction overloading.
Features:
1. Atleasttwofunctionshavesamename.
2. Alloverloadedfunctionsmustbedistinctonthebasisofparameters.
3. Alloverloadedfunctionscanhavesamereturntype.
4. Overloaded functionsare linkedtoitsfunctioncallatcompiletime.
5. Twofunctionsofsamenameandsameparametersarenotpermitted.
Example:Program:u3p1.cpp#i
nclude<iostream.h>cl
assA
{
int
a;float
b;public
:
voidgetdata()
{
cout<<"\nInput integer then real
value:";cin>>a>>b;
}
voidgetdata(intp)
{
a=p;
cout<<"\nInput real
value:";cin>>b;
}
voidgetdata(floatp)
{
cout<<"\nInput integer
value:";cin>>a;
b=p;
}
voidgetdata(intp1, floatp2)
{
a=p1;
b=p2;
}
voidshowdata()
{
cout<<"\nInteger value is
"<<a;cout<<"\nRealvalue is"<<b;

};

Page|46
C++Notes

voidmain()
{
A
ob1,ob2,ob3,ob4;ob1
.getdata();ob2.getd
ata(10);ob3.getdata
(11.2);ob4.getdata(
5,7.5);

ob1.showdata();
ob2.showdata();
ob3.showdata();
ob4.showdata();
}
Output:
Input integerthenreal value: 22 33.4(Enter)
Input realvalue:44.2 (Enter)
Input integervalue:55 (Enter)

Integervalueis22Rea
lvalue is33.4

Integervalueis10Rea
lvalue is44.2

Integervalueis55Rea
lvalue is11.2

Integervalueis5Rea
lvalue is7.5

Inthisprogram getdata()isoverloadedfunctionthatoverload4times.
1. voidgetdata(){}.Itisinvokedbyob1.getdata()
2. voidgetdata(intp){}.Itisinvokedbyob1.getdata(10)
3. voidgetdata(floatp){}.Itisinvokedbyob1.getdata(11.2)
4. voidgetdata(intp1,intp2){}. Itisinvokedbyob1.getdata(5,7.5)
All these functions have same name but different on the basis of parameters. In
thisway defining functions arecalled function overloading. Using
functionoverloadingwedo not rememberto nameofall functions havingsimilartask.

Page|47
C++Notes

Operatoroverloading:
Operator overloading is one more example of compile time polymorphism.
Operatoroperates on numeric data. If operator operates on objects then we say that
operator isoverloadedwithobjects andthis mechanismcalledoperatoroverloading.
Forexample:
Binary + operator can operate numeric data (2+3) as well as operate two objects
ofsameclass (ob1+ob2).
Alloperatorscanbeoverloadedwithobjectsexceptfollowingoperators.
1. Conditionaloperator(?:)
2. Scoperesolutionoperator(::)
3. Sizeoperator(sizeof)
4. Classmemberaccessoperator(.and.*)
Definingoperatoroverloading:
Operatoroverloadingispossibleonlyifthatoperatorisdefinedusingoperatorfunction and
pass objects in the form of arguments. In c++ operator function can bedefinedin
followingtwoways.
1. operatoroverloadingusingmemberfunctionof class
2. operatoroverloadingusingfriend functionof class

Operatoroverloadingusingmemberfunction ofclass:
Using Operator keyword we can define a member function in the class that
performoperatoroverloading. Such functiondefined using followingsyntax:
classcls_name
{
Datamembers
public:
ret_typeoperator±(typearg1,typearg2,…)
{
Apply±operator oneach datamembers
}
};
±maybeanyoperator like+ -/*++--.
Ifoperatorfunctionisdefinedasamemberfunctionthenfirstobjectcalloperatorfunction and
second object passas argument.
Ex:ob3=ob1+ob2willcalloperator+intheformofob3=ob1.operator+(ob2).

Unaryoperatoroverloading:
1. Overloadingunaryminusoperator:
–obj(convertsignofallvaluesofdatamembers)
Example:
Program:u3p2.cpp#inc
lude<iostream.h>clas
sA
{
int a,
b;public:

Page|48
C++Notes

voidgetdata(intp1,intp2)
{
a=p1;
b=p2;
}
voidshowdata()
{
cout<<"\
na="<<a;cout<<"\
tb="<<b;
}
//unary – operator overloading
functionvoidoperator-()
{
a=-a;
b=-b;
}
};
voidmain()
{
A
ob;ob.getdata(10,-
20);ob.showdata();
-ob;//unary –operatoroverloading
ob.showdata();
}
Output:
a=10 b=-20
a=-10 b=20
In this example unary minus(-) operator is apply on object (-ob). At compile time it
isconvertedinto ob.operator-() statement, because operator-() is a member
functionandthis function reverse thesign ofeverydatamembers ofobjectob.
2. Overloadingincrement(++)operator:
Obj++(Incrementvaluesofeachdatamembersbyone)
Example:Program:u3p3.cpp
#include<iostream.h>
classA
{
inta,b;pu
blic:
voidgetdata(intp1,intp2)
{
a=p1;
b=p2;
}
voidshowdata()
{
cout<<"\
na="<<a;cout<<"\
tb="<<b;

Page|49
C++Notes
}

Page|50
C++Notes
// ++ operator overloading
functionvoidoperator++()
{
a+
+;b+
+;
}
};

voidmain()
{
A
ob;ob.getdata(10,2
0);ob.showdata();
ob++; //++operatoroverloading
ob.showdata();
}
Output:
a=10 b=20
a=11 b=21
In this example ++ operator is apply on object (ob++). At compile time it is
convertedinto ob.operator++() statement, because operator++() is a member
function and thisfunctionincrement values ofeverydatamembers byoneofobject ob.
3. Overloadingdecrement(--)operator:
Obj--(Decrementvaluesofeachdatamembersbyone)
Example:Program:u3p4.cpp
#include<iostream.h>
classA
{
inta,b;pu
blic:
voidgetdata(intp1,intp2)
{
a=p1;
b=p2;
}
voidshowdata()
{
cout<<"\
na="<<a;cout<<"\
tb="<<b;

}
// -- operator overloading
functionvoidoperator--()
{
a--;
b--;
}
};

Page|51
C++Notes

voidmain()
{
A
ob;ob.getdata(10,2
0);ob.showdata();
ob--; //--operatoroverloading
ob.showdata();
}
Output:
a=10 b=20
a=9 b=19
In this example -- operator is apply on object (ob--). At compile time it is
convertedinto ob.operator--() statement, because operator--() is a member function
and thisfunctiondecrement values ofeverydatamembers byoneofobjectob.
Binaryoperatoroverloading:(Arithmeticandshorthand operators)
1. Overloading Binary Arithmetic operator: (+,-,*,/,
%)ob3=ob1+ob2
Eachdatamembersofobjectsob1andob2areaddedthenassigntoobjectob3.
Example:Program:u3p5.cpp#i
nclude<iostream.h>cl
assA
{
inta,b;pu
blic:
voidgetdata(intp1,intp2)
{
a=p1;
b=p2;
}
voidshowdata()
{
cout<<"\
na="<<a;cout<<"\
tb="<<b;

}
//
Binary+operatoroverloadingfunctionAopera
tor+(A ob)
{
A
ot;Ot.a=a+ob
.a;Ot.b=b+ob
.b;returnot;
}
};
voidmain()
{
A
ob1,ob2,ob3;Ob1.get

Page|52
C++Notes
data(10,20);

Page|53
C++Notes
Ob2.getdata(1,2);
ob3=ob1+ob2; //Binary+ operatoroverloading
ob3.showdata();
}
Output:
a=11 b=22
In this example binary + operator is apply on object (ob1) and (ob2). At compile
timeitisconvertedintheformofob3=ob1.operator+(ob2)statement,becauseoperator+()
is a member function. This function call by (ob1) and (ob2) is pass
into(ob),therefore(a,b)are data membersof (ob1) and(ob.a,ob.b)
aremembersof(ob2).Inthisfunctionweapplybinary+operatoroneachdatamember(likeot.a
=a+ob.b).Finallyresultingobject (ot)returnsto object (ob3).
2. Overloading Binary shorthand operator: (+=,-=,*=,/=,
%=)ob1+=ob2
Every data members of object ob1 are increases by data members of
objectob2.
Example:Program:u3p6.cpp
#include<iostream.h>
classA
{
int a,
b;public:
voidgetdata(intp1,intp2)
{
a=p1;
b=p2;
}
voidshowdata()
{
cout<<"\
na="<<a;cout<<"\
tb="<<b;
}
//Binary += operator overloading
functionAoperator+=(A ob)
{
a+=ob.a;
b+=ob.b;
}
};
voidmain()
{
A
ob1,ob2;Ob1.getdata
(10,20);Ob2.getdata
(5,7);
ob1+=ob2;//Binary+= operatoroverloading
} ob1.showdata();
Output:
a=15 b=27

Page|54
C++Notes
In this example shorthand += operator is apply on object (ob1) and (ob2). At
compiletime ob1+=ob2 is converted in the form of ob1.operator+=(ob2) statement,
becauseoperator+=() is a member function. This function call by (ob1) and (ob2) is
pass into(ob),therefore(a,b)are data membersof (ob1) and(ob.a,ob.b)
aremembersof(ob2).Inthisfunctionweapplyshorthand+=operatoroneachdatamember(a+
=ob.a).
Operatoroverloadingusingfriendfunctionofclass:
Using Operator keyword we can define a friend function of the class that can
alsoperformoperatoroverloading.Such function definedusingfollowingsyntax:
classcls_name
{
Datamembers
public:
friendret_typeoperator±(type,type,…);
};
ret_typeoperator±(typearg1,typearg2,…)
{
Apply± oneach datamembers
}
±maybeanyoperator like+, -, /,*, ++, --,+=etc.
Ifoperatorfunctionisdefinedasafriendfunctionoftheclasstheneveryobjectwillpassesinto
operatorfunction in theform ofarguments.
Ex:ob3=ob1+ob2willbeconvertintoob3=operator+(ob1,ob2).
Overloading Binary plus(+) operator using friend
function:ob3=ob1+ob2
Eachdatamembersofobjectsob1andob2areaddedthenassigntoobjectob3.
Example:Program:u3p7.cpp
#include<iostream.h>
classA
{
inta,b;pu
blic:
voidgetdata(intp1,intp2)
{
a=p1;
b=p2;
}
voidshowdata()
{
cout<<"\
na="<<a;cout<<"\
tb="<<b;

}
friendAoperator+(A,A);
};

Page|55
C++Notes
//
Binary+operatoroverloadingusingfriendfuncti
onAoperator+(A oa,Aob)
{
A
ot;Ot.a=oa.a+ob
.a;Ot.b=oa.b+ob
.b;returnot;
}
voidmain()
{
A
ob1,ob2,ob3;Ob1.get
data(10,20);Ob2.get
data(1,2);
ob3=ob1+ob2;//Binary+operatoroverloading
ob3.showdata();
}
Output:
a=11 b=22
In this example binary + operator is apply on object (ob1) and (ob2). At compile
timeitisconvertedintheformofob3=operator+(ob1,ob2)statement,becauseoperator+()
is a friend function of class A. In this function object (ob1) and (ob2) arepassed into
(oa, ob) therefore (oa.a, oa.b) are data members of (ob1) and (ob.a, ob.b)are members
of (ob2). In this function we apply binary + operator on each
datamember(likeot.a=oa.a+ob.b).Finallyresultingobject(ot)returnsto object(ob3).
Overloadingnewanddelete:
It is possible to overload new and delete. You might choose to do this if you want
tousesomespecialallocation methodlikemallocfornewandfreefordelete.
ForExample:Program:u3p8.cpp
#include
<iostream.h>#include<
alloc.h>classA
{
inta,b;p
ublic:
A()
{
a=0;
b=0;
}
A(intp1,intp2)
{
a=p1;b=
p2;
}
voidshowf()
{
cout<<"\na="<<a<<"\tb="<<b

Page|56
C++Notes
}

Page|57
C++Notes

//newoverloaded
void*operatornew(size_tsize)
{
cout<< "In overloaded new.\
n";void*p;
p =
malloc(size);retu
rnp;
}
//deleteoverloaded
voidoperatordelete(void*p)
{
cout<<"Inoverloadeddelete.\n";free(p);

}
};
//
voidmain()
{
A*p1, *p2;
p1= new loc(10, 20);
p2 = new loc (-10, -
20);p1->showf();
p2-
>showf();del
ete
p1;deletep2;
}
Output:
In overloaded
newIn overloaded
new1020
-10-20
In overloaded
deleteInoverloadedde
lete
whennewordeleteareencounteredandIfthesehavebeenoverloaded,theoverloadedversion
s areused.
OverloadingSomeSpecialOperators
Arraysubscripting[ ],function calling( ),andclass memberaccess->
Overloading[]
In C++,the [ ]is considereda binaryoperator whenyouare
overloadingit.Therefore,thegeneral formofamember“operator[]()”functionis as
shownhere:
typeCName::operator[](inti)
{
//. . .
}
If obis an object then Ob[3]translates into Ob.operator[](3). That is, the value of
theexpression within the subscripting operators is passed to the operator[ ]() function

Page|58
C++Notes
initsexplicit parameter.
For example, following program has overloaded operator[ ]() function returns
thevalueofthearrayas indexed bythevalueofits parameter.

Page|59
C++Notes

Example:Program:u3p9.cpp#in
clude
<iostream.h>classA
{
int
a[3];publ
ic:
A(inti, int j,int k)
{
a[0]= i;
a[1]= j;
a[2]= k;
}
//Overloading[]
intoperator[](inti)
{
returna[i];//Returnindexing arraydata
}
};
//
voidmain()
{
Aob(1, 2, 3);
cout<<ob[1];// displays2
}
Output:
2
Inthisprogramob[1]translateintoob.operator[1]andthisfunctionreturnob[1]'svalue.
Overloading()
Whenyouoverloadthe()functioncalloperator,thenyouarecreatinganoperatorfunctionthat can
bepassed an arbitrarynumberofparameters.
Forexample:StatementOb(10,23.34,"www.LRsir.net")translatesinto
Ob.operator()(10,23.34,"www.LRsir.net");
Example:
Program:u3p10.cpp#inc
lude
<iostream.h>classA
{
int
a,b;publ
ic:
//Overload () for loc.
Voidoperator()(intp1, intp2)
{
a =
p1;b=p2
;
}

Page|60
C++Notes
voidshowf()
{

Page|61
C++Notes

cout<<"\na="<<a<<"\tb="<<b
}
};
//
voidmain()
{
Aob;
ob(10, 20); //Call Overloaded
()ob.showf();
}
Output:a=
10b=20

Thusob(10,20)willcalloverloaded()function.Andthiswillassignvalues.
Overloading🡪
The 🡪 pointer operator, also called the class member access operator, is considered
aunaryoperatorwhenoverloading.When🡪operatorisoverloadedthenob🡪ClassM
embertranslateintoob.operator🡪().
The following program illustrates overloading the –>by showing the
equivalencebetweenob.iandob–>iwhen operator–>() returns thethispointer:
Example:Program:u3p11.cpp
#include<iostream.h>c
lassA
{
public:
inta;
//Overloaded🡪
A*operator🡪()
{
returnthis;
}
};
//
voidmain()
{
Aob;
Ob🡪a = 10; // same as
ob.acout<<ob.a<<""<<ob🡪a;
}
Output:
10 10
Anoperator🡪()functionmustbeamemberoftheclassuponwhichitworks.
Overloadingthe,CommaOperator
YoucanoverloadC++'scommaoperator.Thecommaisabinaryoperator.When,
(comma)operatorisoverloadedthen(ob1,ob2)translateintoob1.operator,(ob2).

Page|62
C++Notes
Hereisaprogramthatillustratestheeffectofoverloadingthe commaoperator.
Example:Program:u3p12.cpp
#include
<iostream.h>classA
{
public:
inta;
//Overloaded,
Aoperator,(Aob)
{
A
temp;temp.a=ob.a
;cout<<”\
na=”<<a;returnte
mp;
}
};
voidmain()
{
A
ob1,ob2;ob1.a
=10;
ob2.a= 20;
cout<< "\n"<<ob1.a; // display
10cout<<"\n"<<ob2.a;//display20

ob1=(ob1,ob2);//Overloading,operator

cout<< "\n"<<ob1.a; // display 20 of


ob2cout<< "\n"<<ob2.a; //display 20
}
Output:
10
20
20
20
Inthisprogramob1=(ob1,ob2)translateintoob1=ob1.operator,
(ob2).Thisfunctionreturnobject ob2 thatassign ob1.
Overloading<<(Insertionoperator)and>>(Extractionoperator):
Thefunctionsthatoverloadtheinsertion(<<)andextraction(>>)operatorsaregenerallycalle
d insertersand extractors,respectively.
Example:
Program:u3p13.cpp#inclu
de<iostream.h>classA
{
int a,
b;public:
friendistream&operator>>(istream&stream,A&o);frien

Page|63
C++Notes
dostream&operator<<(ostream&stream,A o);
};

Page|64
C++Notes

istream&operator>>(istream&stream,A&o)
{
cout<<"\nInput two
integers:";stream>>o.a>>o.b;
returnstream;
}
ostream&operator<<(ostream&stream,Ao)
{
stream<<"\na="<<o.a<<"\
tb="<<o.b;returnstream;
}
voidmain()
{
Aob1,ob2;
cout<<Input data for two
object";cin>>ob1>>ob2;
cout<<"Data of two objects
are:";cout<<ob1<<ob2;
}
Output:
Inputdata fortwo object
Inputtwointegers:10

20(enter)Inputtwointegers:5

7(enter)Dataof two objects are:


a=10b=20
a=5b=7
Inthisexample>> and<<areoverloadwithobjects.

Page|65
C++Notes

Unit-4
Inheritance:
Theabilitytoaccessmembersofoneclassbyanotherclasscalledinheritance.
Atleasttwoclassesarerequiredforinheritance.
1. Baseclass(Oldclass/
Superclass):Aclassthatprovidesmemberstoanotherclasscalled baseclass.
2. Derivedclass (Newclass/sub class):A classthatcan accessmembersof
baseclasscalled derived class.
Derivedclasscanaccess onlyprotectedandpublic membersofbaseclass.
Typesofinheritance:
InC++,inheritancecanbeimplementedinfollowingways.

Syntaxofderived class:
classderived_class:modebase_class
{
Membersofderived class
};
Here-
:isusedtoconnectderivedclasstothebase class.
Mode/ Base class access control(Access protected member of base class): may
beprivate or protected or public. Default is private. This mode change protected
andpublic members of base into another mode for derived class. It can be explain
usingfollowingtable.
private protectedmodewithd publicmodewithderi
erived ved
modewithderived
privatemembersofbase Notinherited Notinherited Notinherited
protectedmembersofbase Becomesprivate Remainprotected Remainprotected
public membersofbase Becomesprivate Becomesprotected Remainspublic

Page|66
C++Notes
When object of derived class is creates then all data members of base class will
becreates then data members of derived class. Member functions of derived class
canaccessonlyprotectedand publicmembers ofbaseclass.
Example:SingleInheritance(Onebaseandonederivedclass)

Program:u4p1.cpp
#include<iostream.h>
classbase
{
inta; // only usable by
baseprotected:
intb; //usable by base or derived
onlypublic:
voidbgetdata(intp)
{
a=p;
}
voidbshowdata()
{
cout<<"\nInbasea="<<a;
}
};
classderived:publicbase
{
public:
voiddgetdata(intp)
{
b=p; //usesprotectedof base
}
voiddshowdata()
{
cout<<"\nInderivedb="<<b;
}

};
voidmain()
{
derived
od;od.dgetdata(1
0);od.dshowdata(
);

od.bgetdata(20);
od.bshowdata();
}
Output:
In derived
b=10Inbase a=20

Page|67
C++Notes
In this example derived class is publically connected to base class therefore
protectedand public members of base class can be directly used by member
functions ofderived class, that is protected data b is uses by dgetdata() and
dshowdata() of derivedclass.In this classprivatedataaofbaseclass isnot permitted.
When object of derived class is created then first all data members of base class
arecreated then all data members of derived class are created, but private data of
baseclassareonlyvisiblewithin memberfunctionsofbaseclass.
Objectofderivedclasscancallallpublicmemberfunctionsofderivedclassaswellaspublicme
mberfunction ofbaseclass.(dueto publicmode).
MultilevelInheritance:
If it is possible to access protected and public members of base class (grand) by
itsdrive’s(parent)derivedclass(child)thenit iscalledmultilevelinheritance.

Example:Program:u4p2.cpp
#include<iostream.h>
classgrand
{
protected:
intg;
};
classparent:public grand
{
protected:
intp;
};
classchild:publicparent
{
int
c;publi
c:
voidgetdata(intp1, intp2,intp3)
{
g=p1;
p=p2;
c=p3;
}
voidshodata()
{
cout<<"\n data g is of super base (grand) "<<g;cout<<"\
n data p is of intermediate base (parent) "<<p;cout<<"\
ndatacisofderived(child)"<<c;
}
};
voidmain()
{
child
od;od.getdata(10,20,3
0);od.showdata();
}

Page|68
C++Notes
Output:
datagisofsuperbase(grand)10
data p is of intermediate base (parent)
20datacisofderived(child)30

Inthisexample,childisaderivedclassthatcanaccessprotectedorpublicmembersofitsinterm
ediatebase class (parent) aswell ofsuperbase class (grand).
MultipleInheritances:
When one derived class has more than one base class called multiple inheritances.
Itmeans one derived class can access protected and public members of more
baseclasses.

Example:Program:u4p3.cpp
#include<iostream.h>
classbase1
{
protected:
int b1;
};
classbase2
{
protected:
int b2;
};
classderived:publicbase1,publicbase2
{
int
d;publi
c:
voidgetdata(intp1, intp2,intp3)
{
b1=p1;
b2=p2;
d=p3;
}
voidshodata()
{
cout<<"\n data b1 is of base1
"<<b1;cout<<"\n data b2 is of base2
"<<b2;cout<<"\ndatadis
ofderived"<<d;
}; }
voidmain()
{
derived
od;od.getdata(10,20,3
0);od.showdata();
}
Output:
data g is of base1
10data p is of base2
20datacisofderived30

Page|69
C++Notes
Inthisexample,derivedclasscanaccessprotecteddatab1ofbase1classandprotecteddatab2o
fbase2class, thereforeit iscalled multipleinheritance.
HierarchicalInheritances:
When one base class has more than one derived class, called hierarchical
inheritances.It means more than one derived class can also access protected and public
members ofonebaseclasses. (baseisserverandall derived classesareclient)

Example:Program:u4p4.cpp
#include<iostream.h>
classbase
{
protected:
intb;
};
classderived1:publicbase
{
int
d1;publ
ic:
voidgetdata(intp1,intp2)
{
b=p1;
d1=p2
}
voidshodata()
{
cout<<"\n data b is of base
"<<b;cout<<"\ndatad1isofderived1"<<d1;
}

};
classderived2:publicbase
{
int
d2;publ
ic:
voidgetdata(intp1,intp2)
{
b=p1;
d2=p2
}
voidshodata()
{
cout<<"\n data b is of base
"<<b;cout<<"\ndatad2isofderived2"<<d2;
}
};

voidmain()
{
derived1
od1;od1.getdata(10,
20);od1.showdata();

Page|70
C++Notes
derived2od2;

Page|71
C++Notes
od2.getdata(5,7);
od2.showdata();
}
Output:
databisofbase10data d1 is
of derived1 20databisof
base5
datad2is ofderived27
Inthisexample,derived1classandderived2classbothcanaccessprotecteddatabofbaseclass,
thereforeitis called hierarchical inheritance.
Hybridinheritance(virtualbaseclass)
Astructureofinheritancehavingmorethanonetypeofinheritancecalledhybridinheritance.
This structure has one hierarchical inheritance “Grand 🡪(Parent1 and Parent2)”,

onemultipleinheritance“(Parent1,Parent2)🡪Child”andtwomultilevelinheritance“Gran
d🡪Parent1🡪Child”,“Grand🡪Parent2🡪Child.
Problemwithhybridinheritance:
In above type of inheritance, when object of “Child” class is created then
datamembers of “Grand” class are crated two times. One set via “Parent1” class
andother set via “Parent2” class. This causes ambiguity errors if object of “child”
classusesdatamembers of“Grand”class. Thisshouldbeavoided.
Solutionofambiguityproblem:“Virtualbaseclass”
AllmultiplepathsbetweenGrandandChildclass(Grand🡪Parent1🡪Child,Grand🡪Parent2🡪
Child) can be avoided by making a common base class(Grand) asvirtual base class
while declaring intermediate base classes (parent1 and parent2). Duetovirtual
baseclass,onlyonecopyofGrand members arecreatedforChild class.
Implementingvirtualbaseclass:Program:u4p5.cpp
#include<iostream.h>
classgrand
{
protected:
intg;
};
classparent1:virtualpublic grand
{
protected:
intp1;
};
classparent2:virtualpublic grand
{
protected:
intp2;
};

Page|72
C++Notes

classchild:publicparent1, publicparent2
{
private:
intc;
voidgetdata(int w,int x,int y, intz)
{
g=w;p
1=x;p
2=y;c
=z;
}
voidshowdata()
{
cout<<"\ngrand data is
"<<g;cout<<"\nparent1 data is
"<<p2;cout<<"\nparent2 data is
"<<p1;cout<<"\nchilddata
is"<<c;
}
};
voidmain()
{
child
od;od.getdata(10,20,30,4
0);od.showdata();
}
Output:
grand data is
10parent1datais20p
arent2datais30chil
ddata is 40
Inthisprogramgrandclassisdeclaredvirtualbaseclassforchildclassviaallintermediate base
classes parent1 and parent2, therefore when object od of child classis created then
data g of grand class is created only times due to virtual base class
andambiguityproblem doesnot arises.
Constructoranddestructorusedininheritance:
Constructor:
Whenobjectofderivedclassiscreatedthenorderofcreatingdatamembersandinvokingconstruct
orfunctions arefollowing.
1. InSingleinheritance:Firstbaseclassthenderivedclass.
2. Inmultilevelinheritance:Firstsuperbase(grand)thenintermediate(parent)andfin
allyderived.
3. Inmultipleinheritance:Firstfromleftbaseclasstowardsrightmostbaseclassand
finallyderived.
Destructor:
When object of derived removed then order of removing data members
andinvoking destructor functions are reversing of constructors. It means, that last
createdwillfirst remove.
Example:

Page|73
C++Notes
Program:u4p6.cpp
#include<iostream.h>
classbase
{
public:
base()
{ cout<<"\nbaseconstructor"; }
~base()
{ cout<<"\nbasedestructor"; }
};
classderived:publicbase
{
public:
derived()
{ cout<<"\nderivedconstructor";}
~derived()
{ cout<<"\nderiveddestructor";}
};
voidmain()
{
derivedod;
}
Output:
base
constructorderived
constructorderived
destructorbasedestr
uctor
Whenobjectofderivedclasscreatethenfirstconstructorofbaseclasscallsthenofderived.Whenobjec
tremovethenfirstdestructorofderivedcallsthenofbase.
Passingparameterstothebaseclassconstructor:
Whenbaseclasscontainparameterizedconstructorthenwecanpassparameterstobaseconstr
uctorat thetimeofobject creation ofderived.
Example:
Program:u4p7.cpp#inc
lude<iostream.h>clas
sbase
{
protected:
int
a;public:
base(intp) //baseclassconstructor
{a=p; }
};
classderived:publicbase
{
int
b;publi
c:
derived(intp1,intp2):base(p1)
{

Page|74
C++Notes
b=p2;
}

Page|75
C++Notes

voidshowdata()
{
cout<<"\nbase
a="<<a;cout<<"\
nderivedb="<<b;
}
};
voidmain()
{
derived
od(10,20);od.showd
ata();
}
Output:
basea=10
derivedb=20
Itisclearthatthatusing
derived(intp1,intp2):base(p1)
we can pass parameters to base constructor. Constructor header of derived receive
allparametersand wecan pass them to thebaseclass.
GrantingAccess
When a base class is inherited as private, all public and protected members of
thatclass become private members of the derived class. However, we can use one or
moreinherited members to their original access specification. It is possible using
followingsyntaxin derived class.
base::member
Example:
Program:u4p8.cpp#inc
lude<iostream.h>clas
sbase
{
public:
intb;
};
classderived:privatebase
{
public:
base::b;//makeb publicagain
};
voidmain()
{
derivedod;o
d.b=10;
cout<<"\nbaseb="<<b;
}
Output:
baseb=10
Inthisexample,baseisderivedprivatebut wehavetogive grantpublicdatab
ofbaseremainspublicin derivedusing“base::b”.

Page|76
C++Notes

VirtualFunction:(Runtimepolymorphism)
Run time polymorphism is possible using virtual function. In hierarchical
inheritance,it may be happened that same name function headers are defined in base
class as wellas in all derived classes. This situations causes ambiguity when object of
derived classinvokedsuch function.

Dynamicbinding:(Pointertoderived class)
Ambiguitycanbeavoidedbydynamicbindingoffunction.Tocreatedynamicbinding,
address of derived object is assigned to base pointer. At runtime when basepointer call
a function that defined in both classes (base as well as derived)
thenfunctionofbaseclass is bind up.
base
*p;derived
od;p=&od;p🡪
show();
If function is defined using virtual keyword in base class and same function is
alsodefinedin derivedclass thenbasepointer will callfunction ofderived.
Example:
Program:u4p9.cpp#inc
lude<iostream.h>clas
sbase
{
public:
virtualvoidshow()
{
cout<<"\nImdefined inbase";
}
};

classderived1:publicbase
{
public:
voidshow()
{
cout<<"\nImdefinedin derived1";
}
};
classderived2:publicbase
{
public:
voidshow()
{
cout<<"\nImdefinedin derived2";
}
};

Page|77
C++Notes

voidmain()
{
base
*p;derived1
od1;p=&od1;
p🡪show();//Imdefinedinderived1derived2od2;
p=&od2;
p🡪show();//Imdefinedinderived2
}
Output:
I m defined in
derived1Imdefinedinderi
ved2
Ifvirtualkeyword removesthenoutputwillbe:
ImdefinedinbaseImde
finedinbase
In this program, if base pointer holds address of od1 then function of derived1
classwill be invoked and if base pointer has address of od2 then function of derived2
classwill be invoke. If virtual keyword removes then function of base class will be
invokedwhatever addresses holdbybasepointer.
Purevirtualfunction:(abstractbaseclass)
- Pure virtual function: If virtual function in base class does not defined
withcodeandassign by0called purevirtualfunction.
- Abstract base class: A base class that contains pure virtual functions can’t
beused for creating objects, such class called abstract class. The purpose
ofcreatingabstractbaseclassisto providemembersto thederived classes.
Example:
Program:u4p10.cpp#in
clude<iostream.h>cla
ssabstract
{
public:
virtualvoidshow()=0;//purevirtual
};
classderived1:publicabstract
{
public:
voidshow()
{
cout<<"\nImdefinedin derived1";
}
};
classderived2:publicabstract
{
public:
voidshow()
{
cout<<"\nImdefinedin derived2";
}

Page|78
C++Notes

};
voidmain()
{
// abstract ob;
errorbase*p;
derived1
od1;p=&od1;
p🡪show();//Imdefinedinderived1

derived2
od2;p=&od2;
p🡪show();//Imdefinedinderived2
}
Output:
I m defined in
derived1Imdefinedinderi
ved2
Inthisexample,“virtualvoidshow()=0;”iscalledpurevirtualfunctionand“abstract” called
abstract base class because its object class can’t be created and
theirfunctionsaredefined byderived classes.
Earlyvs.LateBinding
Earlybinding:(staticorcompiletimebinding)
Early binding occur at compile time. When we define any function in a program
thenthat function is bind up to its all function call statements during compilation.
Thiseventoccurs beforerunningtheprogram therefore it iscalled earlybinding.
Examples:normalfunction,functionoverloadingandoperatoroverloadingfunctions.
Latebinding:(dynamicorruntimebinding)
Late binding occur at run time of program. When we define any function in a
programthen that function is bind up to its all function call statements during
execution ofprogram. This event occurs after compiling the program therefore it is
called latebinding.
Examplesoflatebindingsarevirtualfunctions.Itispossibleusingbasepointer.

Page|79
C++Notes

Unit-5
TheC++Input/Outputsystembasics:
Every program takes some data as input and generates processed data as
output.InC++ I/Ooperations isdoneusingpredefined streamsand streamclass.
C++streams:
A stream is a sequence of bytes. C++ I/O system operates through streams.
Astreamactsasa logicaldevice thateither producesor consumesinformation.Astreamis
linked to aphysical devicebytheI/Osystem.

It is clear that, a C++ program extracts byte from input stream and inserts bytes
intoinput streams. Input stream reads data from input device (keyboard) and output
streamsendsoutputtothe outputdevice (monitor).Thusstreamsare usedtocreate
aninterfacebetween C++program andI/Odevices.
C++predefined streams:
When a C++ program begins execution, four built-in streams are
automaticallyopened. By default, the standard streams are used to communicate with
the console.Theyare:
1. cin:forstandardinputfromkeyboard
2. cout:forstandardoutput tothescreen
Thebasicstreamclasses:
All C++ I/O operations are performed using console and file streams. All
streamclasses are declared in iostream.hheader file. The hierarchy of I/O stream
classes iniostream.hheaderfileis following.

iosclass is base of istreamand ostreamclasses and these two class are base ofiostream
class. iosis declared virtual base class so that iostream uses one copy of iosmembers.
iosprovides the basic supportsfor formatted and unformatted I/O operations.
istreamclassprovidesfacilitiesforinputdataandostreamprovidesfacilityforoutput.iostrea
mprovides facilities forhandlingboth input and outputs.
For examplecoutstream used for output because it is defined using ostreamclass
andcinis used forinput becausedefined usingistreamclass.

Page|80
C++Notes

UnformattedI/Ooperations:
Overloadedoperators>>and<<
>> operator is overloaded with cinobject for input whereas << is overloaded with
coutobjectfor output operations. >> is overloaded in the istreamclass and << is overloaded in
ostreamclass.
Readingdatafromkeyboard: cin>>var1>>var2>>…..>>varN;
Displaydataonscreen: cout<<item1<<item2<<…..<<itemN;
Example:
Program:u5p1.cpp#inc
lude<iostream.h>void
main()
{
inta,b;
cout<<"\nInput two
values:";cin>>a>>b;cout<<"\
na="<<a<<"\tb="<<b;
}
Output:
Inputtwo values:10

20(Enter)a=10b=20
get()and put()function:
get()defineinistreamclassusedtoreadonecharacterfromkeyboardbycinwhereasput()defi
nein ostreamclass used toshowonecharacteronscreen bycout.
Example:
Program:u5p2.cpp#inc
lude<iostream.h>void
main()
{
charch;
cout<<"\nPress any
key:";cin.get(ch); //read
charactercout.put(ch);//showons
creen
}
Output:
Press any key:
a(enter)a
getline()andwrite()function:
getline() define in istreamclass used to readwhole line of words that end withnewline
character (enter key) by cinwhereas write() define in ostreamclass used
toshowcharacters up togiven limit on screen bycout.

Example:Program:u5p3.cpp#i
nclude<iostream.h>vo
idmain()
{
charline[30];
cout<<"\nInput a line of

Page|81
C++Notes
text:";cin.getline(line,30); //read
linecout.write(line,30); //show30character
}

Page|82
C++Notes
Output:
Input a line of text:
www.LRsir.net(enter)www.LRsir.net

FormattedconsoleI/Ooperations
C+
+supportsanumberofmemberfunctionsforformattingoutputs.Thesefunctionsareclassifie
d into followingcategories.
1. Definediniosclass.
2. usingmanipulators
3. creatingourownmanipulators.
iosFormattedfunctions:iosclasscontainanumberofmemberfunctionsusedto format
output. These functions can be invokedusing coutstream because ostreamisderived
class ofiosclass.
1) cout.width(w):
This member function of iosset the number of columns(w) for the output
ofonlyoneitem.
Example:Program:u5p4.cpp
#include<iostream.h>
voidmain()
{
cout.width(20);//
set10columnscout<<"www.LRsir.ne
t";cout.width(15);
cout<<"openit";
}
output:
w w w . L R s i r . n e t o p e n i t

Thevaluewww.LRsir.net isprintedright justifiedinfirst 20columns,Next itemprintin15


columns.
2) cout.precision(d):
Thismemberfunctionofiossetthenumberofdigits(d)afterdecimalpointoffloatingn
umber.Itis ineffect untilreset.(default precisiondigits are6)
Example:Program:u5p5.cpp
#include<iostream.h>
voidmain()
{
cout.precision(3);co
ut<<2.12178<<"\
n";cout<<3.5004<<"\
n";
}
output:
2.122(rounded)
3.5(not show00)
hereprecisionshowsonly3 digitsaferdecimalpoint.

Page|83
C++Notes
3) cout.fill('*'):
Thismemberfunctionofiosfillsunusedspacesbyany
characterlike*.Itisineffectuntil reset.
Example:
Program:u5p6.cpp#inclu
de<iostream.h>voidmain
()
{
cout.fills('*');cout.width(20);
//set 10
columnscout<<"www.LRsir.net";co
ut.width(15);
cout<<"openit";
}
output:
* * * * * * * w w w . L R s i r . n e t * * * * * * * * o p e n i t

Blankspacesarefilledby*.

4) cout.setf():Thisisamemberfunctionofiosclassthatcanbeusedformultipleformattedout
put.In thisfunction wepass oneortwoflags asarguments.

- cout.set(flag):passonlyoneargument
flag use
ios::showpos Print+beforepositivenumber(+22)
ios::showpoint Show.andzero(2.00)
- cout.set(flag,group):Itisoverloaded formwherewepasstwoarguments.
flag Group / bitflag use
ios::left ios::adjustfield Forleftjustification
ios::right ios::adjustfield Forrightjustification
ios::scientific ios::floatfield Representfloatingnumberlike5E-3

Example:
Program:u5p7.cpp#inclu
de<iostream.h>voidmain
()
{
cout.width(20);//set 10
columnscout.fills('*');cout.pre
cision(2);cout.setf(ios::showpo
s);cout.setf(ios::showpoint);
cout.setf(ios::left,
ios::adjustfield);cout<<23;
}
output:

+ 23 . 0 0 * * * * * * * * * * * * * * *

5) cout.unsetf(flag):thisiosmemberisusedtoclearflagthatsetonpreviousstatement.

Page|84
C++Notes

Manipulators:
Asetoffunctionsdefinediniomanip.hcalledmanipulatorsusedtoformattedoutput.Thesefu
nctions can beused as infollowing form.
cout<<manip1<<manip2<<manip3<<item;
cout<<manip1<<item1<<manip2<<item2;
Therearefollowingsomeimportantmanipulators-
1) setw(w):usedtosetnumberofcolumns(w)offormattedoutput.
2) setprecision(d):usedtosetnumberofdigits(d)afterdecimalpoint.
3) Setfill('*'):usedtofillblankspacebyacharacter like*.
4) endl:usedtosetcurseratnewline.
Example:Program:u5p8.cpp
#include<iostream.h>
#include<iomanip.h>v
oidmain()
{
cout<<setprecision(2)<<12.136;cout<<endl<<setw(20)<<setfi
ll('*')<<"www.LRsir.net";
}
Output:
12.14(rounded)
*******www.LRsir.net
Itisclearthatmanipulatorscanbeusedincoutstatementtoformattedoutput.
CreatingYourOwnManipulatorFunctions
If one type of formatted sequence is required many times then every time we have
torewritesamesequencebeforeshowingitems.Thisisverytimeexpensive.Wecanalso
create our own manipulators using sequence of all required formats. It will beusedin
coutstatement,similarto predefined manipulators.
Syntax:
ostream&manip-name(ostream&stream)
{
//your codehere
returnstream;
}
No argument is used when the manipulator is inserted in
coutstatement.Example1:Set newline+10 columns+Fill blank by*
Program:u5p9.cpp#incl
ude
<iostream.h>#include<
iomanip.h>
ostream&userm(ostream&stream)
{
stream<<"\
n";stream.width(2
0);stream.fill('*
');returnstream;

Page|85
C++Notes
}

Page|86
C++Notes

voidmain()
{
cout<<userm<<www.LRsir.net;cout
<<userm<< "mywebsite";
}
Output:
*******w w w . L R s i r . n e t
******** * * m y * w e b s i t e
Inthisexample,usermisusercreatedmanipulator thatdefinethreeformats.

Page|87
C++Notes

Miscellaneous
Templates
Using template, we can create only one class for any type of data members and
definefunctionsforanytypeofparameters.Atemplatecanbeconsideredasamacro.Weuse
template in placeofall those datatype that have to replace by otherdata types.For
example, following program has a class A that defines integer data members, butwe
want work on float data members then we would be replace every integer type
byfloattype.
Forexample:Program:temp1.cpp
#include<iostream.h>
classA
{
int
a;int
b;publi
c:
voidgetdata(intp1, intp2)
{
a=p1;b=p2
;
}
voidshowdata()
{
cout<<"\
na="<<a;cout<<"\
tb="<<b;
}
intsum()
{
returna+b;
}
};
voidmain()
{
intx=10,y=20,s;A
ob;ob.getdata(x,y)
;ob.showdata();s=o
b.sum();cout<<"\
nSum="<<s;
}
Output:
a=10b=20
Sum=30
Problemin thisprogram:
In this program class has int data members and member function getdata() defines
intparameters, sum() retrunint data. We have to redefine thisclassfor any other
typelikefloat.
Solution:classtemplatesandfunctiontemplates.

Page|88
C++Notes

Classtemplate:Aclasscreatedfromaclasstemplateiscalledtemplateclass.
Classtemplateforone parametertype:templatekeywordisused asaprefix
beforetheclass and Tdefines replacingdatatypein class.
- Syntax fordefiningtemplateclass:
template <class
T>classclsname
{
UseT inplace of datatype
};
- Syntax ofdefiningobject oftemplateclassis
classname<datatype>objectname;A
<int>ob1; or
A<float>ob2;
Exampleofclasstemplateforonetype:Program:temp2.cpp
#include<iostream.h>
template <class
T>classA
{
Ta;
T
b;publi
c:
voidgetdata(T p1,T p2)
{
a=p1;b=p2
;
}
voidshowdata()
{
cout<<"\
na="<<a;cout<<"\
tb="<<b;
}
Tsum()
{
returna+b;
}
};
voidmain()
{
A<int>
ob1;A<float>o
b2;
cout<<"\
nworkingwithintegerdata:";ob1.getdata(10,20);
ob1.showdata();in
ts1=ob1.sum();
cout<<"\nSum="<<s1;cout<<"\

Page|89
C++Notes
nworkingwithfloatdata:";Ob2.getdata
(5.2,6.3);

Page|90
C++Notes
Ob2.showdata();floa
ts2=ob2.sum();cout<
<"\nSum="<<s2;
}
Output:
workingwithintegerdata:
a=10b=20
Sum=30
workingwithfloat data:
a=5.2

b=6.3Sum=11.5
Nowinthisclass Acanbeused for anydatatypewhere wehaveto define templateT.
Classtemplatefor multipleparametertypes:
T1,T2etccanbeusedformultipletypes.
- Syntax fordefiningtemplateclassformultipletypes:
template<classT1,classT2,..>cla
ssclsname
{
UseT1,T2,..inplace ofdata types
};
- Syntax ofdefiningobject oftemplateclassis
classname<type1,type2>objectname;
Firstintandsecondfloat:A<int,float>ob1;
Exampleofclasstemplatefortwotype:
Program:temp3.cpp
#include<iostream.h>
template<classT1,classT2>classA
{
T1a;
T2b;
public:
voidgetdata(T1p1, T2p2)
{
a=p1;b=p2
;
}
voidshowdata()
{
cout<<"\
na="<<a;cout<<"\
tb="<<b;
}
T2sum()
{
returna+b;
}

Page|91
C++Notes
};

Page|92
C++Notes

voidmain()
{
A<int,float>ob1;
cout<<"\nworking with multiple
types:";ob1.getdata(10,20.2);
ob1.showdata();flo
at
s=ob1.sum();cout<<
"\nSum="<<s;
}
Output:
workingwithmultipletypes:
a=10b=20.2S
um=30.2
classAcanbeusedforanytwo datatypesusingtemplateT1 andT2.
Function template: Like class template, we can also define function
templatesthatcouldbeused tocreateafamilyoffunctionswith differentargumenttypes.
- Syntaxfordefiningfunctiontemplate:
template<classT>
ftypefname(argumentsof Ttype)
{
Bodyof functionused argumentsof Ttype
};
Exampleofswappingof anytwonumbers of anytypes.
Program:temp4.cpp
#include<iostream.h>
template <class
T>voidswap(T&x,T&y)
{
Ttemp=x;x
=y;y=temp
;
}
voidmain()
{
int
a=10,b=20;floatp=2
.2,q=3.4;
swap(a,b);//pass
integersswap(p,q);//pass floatscout<<"\
nInteger:a="<<a<<"\tb="<<b;cout<<"\
} nFloat:p="<<p<<"\tq="<<q;
Output:
Integer:a=20

b=10Float:p=3.4
b=2.2
Inthiswayusingfunction templatewecanpassdifferent typesofparameterstoonefunction.

Page|93
C++Notes

FilehandlingI/OoperationinC++:
Fileisacollectionofcharacterssavedinsecondarymemory(harddisk)withsomeproperties(attribute
s).
Fileattributes:
1. Filename(Ex:myfile)
2. Fileextension(Ex:.txt)
3. Dateandtimeof filecreation &Modification(Ex:1/24/167:22pm)
4. Sizeoffile(Ex:2KB)
5. Fileaccesspermission(Ex:Read/Write/Execute)etc.
FileOperations:
1. CreateandOpennewfile(loading)
2. Openexistingfile
3. Writingdatato thefile
4. Readingdatafromfile
5. Searchingdataonfile
6. Closingfile
Filetypes:(BinaryfileandText file)
For the same content size of these two type of files are different because
variouscharactertranslation occurs in text modefile.
Filestreamclassesandheaderfile:
- ifstreamforreadingdata fromfile,
- ofstreamforwritingdatatothefile
- fstreamforreadorwrite operation tothefile
Allthesefilestreamclassesaredeclaredinfstream.hheaderfile.
Openingand closingfile:Beforeopeninga file,wemustfirstobtainstreams.
1) ifstreamfr; //toreadfiledata
2) ofstreamfw; //towritedatainfile
3) fstreamfrw; //forreadandwritedata offile
fr, fw and frw are file stream used to open and read / write operation on
file.Syntax: stream.open("filename",mode);
Modesetfilepointerpositionandtypeof file.
Mode applicable_stream_class use_and_pointer_position
ios::in istream/fstream readandbeginning
ios::out ostream/fstream writeandbeginning
ios::app ostream/fstream appendandend
ios::ate all appendandendbutcanmovebeg
ios::binary all open in binarymode(defaultis text)
ios::trunc ostream removecontentofexistfile

Page|94
C++Notes
closing the file: After read / write operation on file, file should be unload
frommemoryusingclose()function offilestreamclass.
Syntax: stream.close();
Example1:Openfileonlyinreadmode
ifstreamfr;fr.open("f
ile1.txt");
//or
fr.open("file1.txt",
ios::in);if(!fr)
{
cout<<"\nunableto openfile";
//handleerror
}
---readoperation-------
fr.close();
Example2:Openfileonlyinwritemode
ofstreamfw;fw.open("f
ile1.txt");
//or
fw.open("file1.txt",
ios::out);if(!fw)
{
cout<<"\nunableto openfile";
//handleerror
}
---writeoperation-------
fw.close();
Example3:Openfileonlyin appendmode
ofstream
fa;fa.open("file1.txt",ios::ap
p);if(!fa)
{
cout<<"\nunableto openfile";
//handleerror
}
---appendoperation-------
fa.close();
Example4:Openfileinbinaryand writemode
ofstreamfw;fw.open("file1.txt",ios::binary|
ios::out);if(!fw)
{
cout<<"\nunableto openfile";
//handleerror
}
---binarywriteoperation-------
fw.close();

Page|95
C++Notes

Using<< and>>
Writingtexttothefileusing<<:
Program:file1.cpp
#include<iostream.h>
#include<fstream.h>v
oidmain()
{
ofstreamfw;fw.open("f
ile1.txt");if(!fw)
{
cout<<"\n unable to open
file";return;
}
fw<<"www.LRsir.net\n";//writetexttothefile
fw.close();
}
Whenthisprogramexecutesthenfile1.txtcreates incurrentlocationandcontent
www.LRsir.netwillbewriteintofileusing<<insertionoperator.
Readingtextfromthefile>>:
Program:file2.cpp
#include<iostream.h>
#include<fstream.h>v
oidmain()
{
ifstreamfr;fr.open("f
ile1.txt");if(!fr)
{
cout<<"\n unable to open
file";return;
}
chartxt[50];
fr>>txt;//readtext fromfile
cout<<txt;f
w.close();
}
Output:www.LRsir.net(Readfromfile1.txt)
Usingput()andget()
Writingcharacterto thefileinbinarymodeusing put():
Program:file3.cpp#in
clude<iostream.h>#in
clude<fstream.h>void
main()
{
ofstreamfw;fw.open("file1.txt",ios::out|
ios::binary);

Page|96
C++Notes

if(!fw)
{
cout<<"\n unable to open
file";return;
}
charch;
cout<<"Type text: (Press ! to
stop)";while(1)
{
cin.get(ch);if(ch
=='!')break;fw.pu
t(ch);
}
fw.close();
}
Contentsarewritetothe file1until!mark.
Readingcharacterfromfilein binarymodeusing get():
Program:file4.cpp#in
clude<iostream.h>#in
clude<fstream.h>void
main()
{
ifstreamfr;fr.open("file1.txt",ios::in|
ios::binary);if(!fr)
{
cout<<"\n unable to open
file";return;
}
charch;
while(fr)//falsewheneof
{
fr.get(ch);
cout.put(ch);
}
fr.close();
}
Contentsarewritetothe file1until!mark.
Usingwrite()andread()
Writingdifferenttypeof data tothefileinbinarymodeusingwrite():
Program:file5.cpp#in
clude<iostream.h>#in
clude<fstream.h>#inc
lude<string.h>

structemployee
{
intid;
char
name[20];float
sal;
};

Page|97
C++Notes

voidmain()
{
employee
emp;emp.id=10
1;
strcpy(emp.name,"Lokeshrathore";e
mp.sal=30000.34;
ofstreamfw;fw.open("file1.txt",ios::out|
ios::binary);if(!fw)
{
cout<<"\n unable to open
file";return;
}
fw.write((char*)&emp,sizeof(emp));
fw.close();
}
Readingdifferenttypeof datafromfilein binarymodeusingread():
Program:file6.cpp#in
clude<iostream.h>#in
clude<fstream.h>#inc
lude<string.h>struct
employee
{
intid;
char
name[20];float
sal;
};
voidmain()
{
employee
emp;ifstreamf
r;
fr.open("file1.txt",ios::in|ios::binary);if(!
fr)
{
cout<<"\n unable to open
file";return;
}
fr.read((char*)
&emp,sizeof(emp));cout<<emp.id<<"\
n";cout<<emp.name<<"\
n";cout<<emp.sal<<"\n";

fw.close();
}
Usinggetline()
Readinga lineupto \n characterfromfilein binary modeusing getline():
Program:file7.cpp#in
clude<iostream.h>#in
clude<fstream.h>void

Page|98
C++Notes
main()
{

Page|99
C++Notes
ifstreamfr;fr.open("f
ile1.txt");if(!fr)
{
cout<<"\n unable to open
file";return;
}
char
str[255];str=fr.g
etline();cout<<st
r;fr.close();
}
Contentsofonelineare readfromthe file1.
eof() function(detecting end of file): EOF is termination character of
everyfile.When pointerreaches toEOFtheneof()functiongives truevalue.
if(fr.eof())
cout<<"Fileends";
ignore()function: ignorereadinguptogivennumberofcharacterorgivencharacter.
Following code ignores character until space is encounter or 10 charactershavebeen
read.
fr.ignore(10,'');
peek()function:givesnextcharacterofread stream.
charch=fr.peek();
chhasnext character(maybeEOF)
putback()function:giveslastreadcharacterfromareadstream.
charch=fr.putback();
chhasprevious character.
flush()function:forcewritestreamdatatothefilebeforeclosingfile.
fw.flush();
seekg() function: set read stream at given offset addess for next
readoperation.
fr.seekg(offset,origin);
originmay be
ios::begbeginning of
fileios::curcurrent
locationios::endend of file
seekp() function: set write stream at given offset addess for next
writeoperation.
fstreamfrw;frw.open("file1.txt",ios::in|ios::out|
ios::binary)frw.seekp(offset,origin);//fstream
tellg()andtellp():returncurrentfileposition.

Page|100
C++Notes

Exceptionhandling:
At run time program can gives error due to some statement like m/n and n
maybe 0, opening file then program can be terminated from that point and
remainingstatementsdoes not executed.It is called exception.
WecanhandlesuchexceptioninC++programusingtry-catchblock.
Syntax:
try
{
//codecreatesexception
}
catch(typearg1)
{
//errormessagewithvalue
}

All the statements that create exception should be defined in try block. If
exceptionoccurred then it is thrown to the catch block with exception value. In this
block wetrace type of exception and show message to user. After then remaining
statementscontinuedforexecution.
Example:
Program:excep1.cpp#inclu
de<iostream.h>voidmain()
{
intc, a, b;
cout<<"input two
number:";cin>>a>>b;
try
{
c=a/
b;cout<<
c;
}
catch(inti)
{
cout<<"\nException occurs";cout<<"\
nExceptionvalueis"<<i;
}
}
Output1:
inputtwo number:10

0(enter)Exceptionoccurs
Exceptionvalueis 1
Output2:
inputtwo number:10

2(enter)5
Remark:Notsupported inTurboC++Compiler.

Page|101

You might also like