Oops Using C++ Unit 1-4
Oops Using C++ Unit 1-4
iexceptthi3 function
ofthot class.
Encapsulation In
0oP,Encapsulation iS defined as binding
together the dota an the functions tht manîpulateg ten
Dyma mie
Binding dynamic bindin, h e Code to
be exe cu+ed An desponse Fuhctioncall 3
decide af un time
create3
has Some ame ag l a s s Rtse .5.GHu
tha class
Can be acce ssed
y
Note Tf we do not S peci ty dny
Ccess
modifier
detauit he acce s3
1nside the Class then by
member
wiil be PTVGtE
modi fier he
Friend elass A tinend Coss can aceess PTvate
of other CloSS in Which
and protected mem bers
declared aS riend
riend alass B
Inhe ritancE
Class SubclasS 3 acess m ode bose class
Sinq e heritance
A
desiqrin detai3.
loca lass
Al the methoð3 ot (ocal clasS must k ë detne2d
base aos3
n Ct+
Exceptfon Handlinq
block of Code hat Can MTO WM
represet a
an exception
block Of Code that q e Executed
Catch eptesunt
error S hrow n
When
how Used On xceptib N
nere Speci aliCa
a blocK Cacn* )
+catches all type3 Ot erYOT
n ne
etunntype fun
<c endl,
main
print(1o);
print (lo-i2)
pifferences b/ e ano Cr+
213dmC*T
CSupport3 Procedural proa Ctt iS Known as ny brid
tramquoge,9/dbeca vse 1t ort
both proceduraland object
oriented prog ramming
a. As Cdoes not SuPPort he C++ has Upport for poly mr
oofs Com cept has mn6 phis, encapsulation0 and
Support for polymorphism, 1nheita nce as t g an
encapsulath on and in heritance. oofs anquaqep tore
languaoe.
6 Func+ion and operator over (oading C++ sUPport 3funtion
mot SPPort in C. Operator overlodding.
Tot Sopport exception daes SoPPort
7. does
hand linaq O CREEDtion hondin Usin
and atch
of dissimjlar elgmentg
StructTUre 18 a Collection
*
Static Members n
Ex elass
Accov
prtvate
balance;
Static TO
publie
Void setBalance Cimt b)
baonce =bj
Accountai
Dbjec+ con aso be decloredd aB 3tatic.
Statlc Account aL
ConshructorB
9'gm)+nl
ConstYUCtor8 On
special mem ber. yfun ctionprof me
Class. Tt i3 au tomatcolly nvo Ked when an object
iS created.
I has no Teturn
type
ConsS+ructor has Same Mame asClasS Hse
C++
TF we do ot spea fy en o mpiler generates
a default Comt rvctor tor
Constrvctor
Defoult Parometerized
CoPY
Classnamel) Cass-name (panameter2 9.CAsname (ong8t
Class-na me ob
updateC) S
UpdakelN*K, nt q) TUpdate(Constüpdate
YS9Y
a=p2.a;
rp b 20 b
enerates wo ConstUCHOr by Se
Compiler
1 Defau bnstructor
3.
Co Con strUCTOr
any of he onstructor
cratEd
by user,
defau + Constructor wil be CYeate by
then
Compi er.
Construction over loqding Can be done ust+
fonction overloqding
CPoint3 o Same
memory o ation)
ob) obj 2
Can we
make opy Consthructor priate ?
Yes
Why argument to Copy Constructor must be passed
a ° referene ?
Because we
pass vatue Men T Woul d ma de
PO
Deep CopP
Desructor
DesthUCtds a
delet es
member functlon Which destUCt 3 or
ans objectF
DesYuctos don+ ake any araument and don'+
hae ny retuYn type
only one destrUctor Poss ible
Des+TUCtor conno* DE
Soric
Actuall destrtor doezn't
destroy object i t
i3 me last
Func tion that invOked before object desry
ODjecF Kesource
Class omple2X
'
in main C)
C+c2
As + directly So W
CompleX no'3
Con+ add
Con define afunctton With ma me bot we
Friend Ciass
A friend ela8s Can the Pri vate and
OcegS pro tected
members Other class i n Nhich + daclared 93
friend.
There an De riend elass a n d riend tunctr on
Ex ClaCs Box
private
dauble width
Public
friend YoidprintW idth (Box box)
Noid SetWidi( davble wia)
mainC)
Box box
bx setWidti 4);
printWcth box)D
Tnher?tance
proce88 of in herhnq prope rties and behaviour
of existinq class into d ne lass.
VisibiiryMode
of Tnneñtance
ypes
Q).
Single Tnheritance :
class B Public A
Inherl-ance :
b). Multilevej
public A
Class 8
3
class C poblic B
Tnhertance 3 b i AL
C). myltiple
ass AL Closs A2
Clo ss B1:Public A
61-i
282
cloSS 82 Public A
9enic
Visibilty Mode :
Private
Protectd
A bose alossS Publle
- Sub Class
A
Private A
leotecka
-Kbliet
rinte> Publie
rotectes
vate
Sub CloBs
andNisibitiry Mode Public.
eloss
1S a
Relationship always mplenm ented aB a
public n heri t nce
BC) AC)
ConstruCtos exer,
A d Const
While n ase e desesU Ctos,
exea
fHrt chi ld destrvctos
farent Con&
then arent 'des. exeCuted.
Complete pora
Comple+e d u |
this Pointer
Every object in CT has access to 113 own addre 83
mrouan an
imortat pointer aalled thi poimter
Class Box
private
9,b,h
Poblie
NoldY2I$et C Int 2:Ant b nt a)uite
hig> =
thisab b
this hn h
i t mgin C)
Box
S hee
vedei nition of base cksS
in
fonc+ ion
derived cla 33, with Same
return and same
parameter3
whíle method
NerloadingtnS achieved at Gompile ime.
Clo83 Cor
private
nt qearno
Publt
Yoiid
ge-(jnt aer
ear+t
enr+
main
S p o r t s Car
Version ot me fonction
e osS base
Sublic
vfrtval void print C)
"
Void Show
Coutcc Bose Show fon ee
endlG
clasS derived
publicsi 1i n
Noid printC)
CoUt <e:" deriived sint eend1
Void showc)
doestwo mings
obj i8
(veTR)s ereated every ime
A Virtual pointer
that Class which Comains V iftual toncion
ereated
deriNcd Ca sg
Class an d
durnng Eorny binding
inidyr
Some+íme3 mplementation Of all funcrion n not be proyit
n the base Class , Such aCoss is CAled abstaet class
drawO
Shape (Bct here
im plementatton
Cant be ony
et draw
e angie Square tun n base ttass
ABStroct Cla ss
public
orS Virt ual fun cHon
virtugl void Tun l) =0
A aloss is
abstra ct 14 + has at legs onc
.pUre virtual:fon etion
We cannaDt declare obect ofObs troct elo 83
Ex Test Wil eror
Show
We an dccesS
he Omer fun ctions CKcept Virttaa
by object of i tS deived elass
we dont Override tme Purevirtua foneHon
in derived clasp hen it becomes a h s a d t
5. An abstract Class Con naNe ConstruCtorB
CRead 4rom GfG)
Templete in C +
Ca>b)
TErvrn aj
ei8e TerUT n b,
maln ()
geers
new aeeks)
OBJECT ORIENTED
PROGRAMMING
(with C++)
1. ADA
2. C++
3. Java
4. C# (C sharp)
Most of them also supports full syntax of
procedure oriented programming .
Each of them supports object oriented
features to varied degree.
single line //
e.g/* this is
documentation*/
3. Spaces and tabs can be inserted anywhere to
increase readability
e.g a=12*b-(c/2) is same as 12 * b –( c / 2)
1. Standard C library.
2. Class library(that supports object
oriented programming)
Identifiers
Constant
Operators
Double,new,else,if,break,continue,long,
int,float,for ,while,class,inline,struct,void etc.
Operator Action
&& AND
|| OR
! NOT
Addition(+)
Subtraction(-)
Multiplication(*)
Division(/)
Modulus(%)
Unary minus(-)
Unary Plus(+)
Built-in User-defined
Structure
Integer
Derived
Union
Character Array
Float Class
Pointer
Enumeration
Void Reference
int main()
{…..
int sum=32 ,number=4;
………
float average=sum/number;
}
while
For Iteration/Loop
Break
Continue
go to Jump
Return
}
OOPS (Unit - 1) Dr. Gaurav Gupta 43
Questions
ANS C
OOPS (Unit - 1) Dr. Gaurav Gupta 44
2. Which is true about C and C++?
a. C is a superset of C++
b. C is a subset of C++
c. Both have different spaces
d. Both are same
e. None.
ANS B
ANS 1, 3 and 4
OOPS (Unit - 1) Dr. Gaurav Gupta 47
5. Which syntax is not correct in C++?
a. For(a=1,b=3;a*b<100;a++);
b. Switch (char array)
{case “abc”: ……;break;}
c. for(;;){ statements…..}
d. For(;a<10;a++);
e. For (int a=1;a<13;);
f. All of the above
ANS b
name is default
no is23
Unit-3
Generic Function
Unit-4
Exception Handling
class Test {
public:
Test() { cout << "Constructor of Test \n"; }
~Test() { cout << "Destructor of Test \n"; }
}; Output:
Constructor of Test
int main() { Destructor of Test
try { Caught 10
Test t1;
throw 10;
} catch(int i) {
cout << "Caught " << i << endl;
}
}
Unit-4
Standard Library, Streams & File
endl
To insert new line and flush stream
cout<<endl;
cout<<setiosflags(ios::scientific)<<1.0000;
Output: 1.0000e+000
resetiosflags(long f)
Clears the flag specified by setiosflag e.g.
cout<<resetiosflags(ios::scientific)<<1.0000;
Output: 1.0000
e.g.
.width ( ) ;
Specify field width. (Can be used on input or output, but
only applies to next insertion or extraction).
e.g.
cout.width (4) ; // field is four positions wide
.fail ( ) ;
Tests if a stream operation has failed.
e.g.
cin.fail ( ) ; // true if a format error occurred
! cin; // same as above; true if format error
e.g.
cin.clear ( ) ; // allow I/O to resume on a "bad"
// stream, in this case "cin",
// on which error had previously
// occurred
Unit-4
Standard Template Library
Function Objects
Iterators
Containers Containers
#include<iostream>
#include<numeric>
#include<vector>
using namespace std;
int main()
{
vector<int> v(10); /* now vector v is : 0,0,0,0,0,0,0,0,0,0 */
iota(v.begin(), v.end(), 10 ); /* now the vector v is
10,11,12,13,14,15,16,17,18,19 */
}