Professional Documents
Culture Documents
Aim: To understand the concepts of object-oriented programming and master OOP using C++ Unit I
300
9 Object oriented programming concepts ! objects ! c"asses ! methods and messages ! abstraction and encapsu"ation ! inheritance ! abstract c"asses ! po"#morphism Introduction to C++ ! c"asses ! access specifiers ! function and data members ! defau"t arguments ! function o$er"oading ! friend functions ! const and $o"ati"e functions ! static members ! Objects ! pointers and objects ! constant objects ! nested c"asses ! "oca" c"asses Unit II 9 Constructors ! defau"t constructor ! Parameteri%ed constructors ! Constructor &ith d#namic a""ocation ! cop# constructor ! destructors ! operator o$er"oading ! o$er"oading through friend functions ! o$er"oading the assignment operator ! t#pe con$ersion ! e'p"icit constructor Unit III 9 (unction and c"ass temp"ates - E'ception hand"ing ! tr#-catch-thro& paradigm ! e'ception specification ! terminate and )ne'pected functions ! )ncaught e'ception Unit IV 9 Inheritance ! pub"ic* pri$ate* and protected deri$ations ! mu"tip"e inheritance ! $irtua" base c"ass ! abstract c"ass ! composite objects +untime po"#morphism ! $irtua" functions ! pure $irtua" functions ! +TTI ! t#peid ! d#namic casting ! +TTI and temp"ates ! cross casting ! do&n casting Unit V 9 Streams and formatted I,O ! I,O manipu"ators - fi"e hand"ing ! random access ! object seria"i%ation ! namespaces std namespace ! -.SI String Objects ! standard temp"ate "ibrar# Total: 4 TE!T BOO"S: / 0 Tri$edi* 1Programming &ith -.SI C++2* O'ford )ni$ersit# Press* 3445 RE#ERENCES: / Ira Poh"* 1Object Oriented Programming using C++2* Pearson Education* Second Edition +eprint 3446 3 S 0 7ippman* 8osee 7ajoie* 0arbara E 9oo* 1C++ Primer2* (ourth Edition* Pearson Education* 344: ; 0 Stroustrup* 1The C++ Programming "anguage2* Third edition* Pearson
Unit I
Object oriented programming concepts ! objects ! c"asses ! methods and messages ! abstraction and encapsu"ation ! inheritance ! abstract c"asses ! po"#morphism Introduction to C++ ! c"asses ! access specifiers ! function and data members ! defau"t arguments ! function o$er"oading ! friend functions ! const and $o"ati"e functions ! static members ! Objects ! pointers and objects ! constant objects ! nested c"asses ! "oca" c"asses
Objects
An o$%&'t i( an &n'a)(*lation o+ $ot, +*n'tion( an- -ata
Objects are an Abstraction represent real world entities Classes are data types that define shared common properties or attributes Objects are instances of a class -"" objects ha$e attributes (characteristics)* this is sometimes referred to as state Objects have State have a value at a particular time Objects have Operations associated set of operations called methods that describe how to carry out operations (behavior) Objects have Messages request an object to carry out one of its operations by sending it a message messages are the means by which we exchange data between objects
;
Cla((&(
Cla(( : <hate$er &e can see in this &or"d a"" the things are a object -nd a"" the objects are categori%ed in a specia" group That group is termed as a c"ass C"ass has man# other features "i=e creation and imp"ementation of the object* Inheritance etc
c"asses
E$er# object be"ongs to (is an instance of) a c"ass -n object ma# ha$e fie"ds* or $ariab"es
The c"ass describes those fie"ds
The operations defined b# the ->T are the only operations permitted on its data E'amp"e? a CheckingAccount* &ith operations
Object-Oriented Concept
The rectang"e area prob"em >efine a c"ass? +ect
>ata? &idth* "ength (unctions? computeEarea()
Encapsu"ation
class Circle { private: int radius public: Circle(int r); // The area of a circle int compute_area(); }; }; class Trian le { private: int ed ea! ed eb! ed ec; public: Trian le (int a! int b! int c); // The area of a trian le int compute_area();
"#ample Code
class $ect { private: int %idth! len th; public: $ect (int %! int l) { %idth & %; len th & l; } int compute_area() { return %idth'len th; } }
M&t,o-( 0 M&((a1&(
G
S&n-in1 a m&((a1& i( o*2 3a4 o+: ! int&2a'tin1 3it, o$%&'t(5 ! mani)*latin1 an o$%&'t6( (tat&5 T&ll( t,& o$%&'t 3,at to -o 3it, it(&l+ E7am)l&: To ',an1& t,& ',ann&l on TV ! 8& *(& t,& ',ann&l (&l&'tion $*tton( 9T,i( (&n-( a m&((a1& t,at 3& 3ant to (&l&'t a n&3 ',ann&l ! T,& TV 2&()on-( to t,& m&((a1& $4 (&l&'tin1 an- &7&'*tin1 a method. ! T,& TV no3 2&'&i:&( a n&3 (i1nal 3,i', i( t,& ',ann&l 3& (&l&'t&-
M&t,o! T&ll( t,& o$%&'t ,o3 to 2&()on- to a m&((a1& O*2 TV.0/ o$%&'t( 2&()on- to t,& +ollo3in1 m&((a1&(: ! T*2n t,& t&l&:i(ion (&t on o2 o++ ! C,an1& t,& ',ann&l ! C,an1& t,& :ol*m&
Characteristics of OOP7
En'a)(*lation: Combining data structure &ith
actions
>ata structure? represents the properties* the states* or characteristics of objects -ctions? permissib"e beha$iors that are contro""ed through the member functions
hiding? Process of ma=ing certain data inaccessib"e In,&2itan'&: -bi"it# to deri$e ne& objects from o"d ones
>ata
permits objects of a more specific c"ass to inherit the properties (data) and beha$iors (functions) of a more genera",base c"ass abi"it# to define a hierarchica" re"ationship bet&een objects
-bstraction C"asses Encapsu"ation C"asses Information Hiding Pub"ic and Pri$ate 9embers Po"#morphism Operator o$er"oading* temp"ates* $irtua"
OOP (eatures
6 major features in OOP
encapsu"ation information hiding inheritance o$er"oading
Encapsu"ation
an o$%&'t &n'a)(*lat&( $ot, it( att2i$*t&( 0 m&t,o-( imp"ications?
an attribute, method is attached to an object, c"ass &hen #ou mention an attribute, methods* #ou ha$e to specif# &hich object, c"ass it comes from
&h# encapsu"ationI
&hen #ou get ho"d of an object* #ou a"so get ho"d of its data & beha$iour components good for reuse
Information Hiding
an o$%&'t 'an ,i-& it( int&2nal -&tail(
e g #ou donJt =no& ho& #our mobi"eJs e"ectronics &or=s e'cept punching the buttons
Inheritance
a 'la(( ma4 $& (imila2 to anot,&2 'la(( $*t $&in1 mo2& ()&'iali(& e g the c"ass 1student2 is simi"ar to the c"ass 1person2 but 1student2 is more specia"ised
a person has attributes "i=e? se'* age* name a student has a"" these + a student no
Inheritance (contJd)
a subclass
e'tends, specia"ises a superclass inherits attributes & methods from its superclass ma# ha$e more attributes, methods than its superclass ma# change the content, procedure of an inherited method
i e same method name, signature but different beha$iour
&h# inheritanceI
reuse e'isting c"ass definition customise, specia"ise if needed
O$er"oading
different functions, procedures, methods can ha$e the same name
pro$ided that the parameters are of different t#pes
gi$ing a uniFue 1signature2
the s#stem &i"" figure out &hich one to in$o=e e g #ou can ha$e 3 procedures* both named 1call2* ta=ing a 1dog2 or 1person2 object as parameter respecti$e"# >epending on #ou gi$e it a 1dog2 or 1person2 object as the parameter* 8a$a &i"" =no& &hich one to use
<h# O$er"oadingI
#ou can ca"" the same method (name) but in$o=e different beha$iour
d#namic binding of method
&hich method to in$o=e is determined at runtime
code reuse
in term of the 1ca""ing2 code
Encapsu"ation is the mechanism that binds together code and data* and =eeps both safe from outside interference or misuse / 0oth data and member functions treated as sing"e unit 3 -bstract focuses on beha$ior of object* encapsu"ation focuses on actua" imp"ementation ; Encapsu"ation achie$ed through data hiding 6 (or abstractions to &or=* imp"ementations must be encapsu"ated
-bstract T.pes
class /hape { public: /hape(); // Calculate the area for // this shape virtual int compute_area() & 0; };
-d$antages of >ata -bstraction and >ata Encapsu"ation Simp"ification of soft&are de$e"opment Testing and >ebugging +eusabi"it# 9odifications to the representation of a data t#pe
-bstract Classes
6a. Contain abstract methods /ome methods and data ma. be defined abstract class Coloured/hape { private Colour c; // stora e allocated for each public abstract void dra%(); public Colour etColour() { return c; } public abstract void erase(); } 7o instances allo%ed /ubclasses must implement all abstract methods or the. are also abstract
#ort a e
$oan
29 of 10 slides
OO Conce!ts Overvie"
A Class
Encapsu"ation Hides the imp"ementation detai"s of a c"ass (orces the user to use an interface to access data 9a=es the code more maintainab"e -PI doc as an e'amp"e
int sum_area(/hape s(! /hape s9) { return s(+compute_area() : s9+compute_area(); // "#ample of pol.morphism }
27T$;1<CT2;7 T; C::
2nherit all -7/2 C directives 2nherit all C functions
comments
/* You can still use the old comment style, */ /* but you must be very careful about mixing them */ // It's best to use this style for 1 line or partial lines /* And use this style when your comment consists of multiple lines */
C7-SSES
-ccess specifiers
Specif# &hether the data defined &i"" be a$ai"ab"e to the users of the objects of the c"ass Pub"ic Pri$ate Protected Pub"ic? the data defined under pub"ic is a$ai"ab"e to objects Pri$ate? data defined under pri$ate is not a$ai"ab"e to objects
C"ass student A Pub"ic ? int +o"".oB pri$ate? string nameB string addressB pub"ic? $oid Print>etai"s() A cout CCro""noB cout CCnameB cout CC addressB D DB $oid main() A student student/B student/ +o"".oM 5B student/ nameM 1N2B ,, does not &or= since name is pri$ate student/ addressM 1O2B ,, does not &or= since name is pri$ate Student/ Print>etai"s()B D
C"ass student A Pub"ic ? int +o"".oB string nameB string addressB $oid Print>etai"s()B DB
,,protot#pe
$oid student ?? Print>etai"s() A cout CCro""noB cout CCnameB cout CC addressB D DB $oid main() A student student/B student/ +o"".oM 5B student/ nameM 1N2B student/ addressM 1O2B Student/ Print>etai"s()B
D
c"ass student A pub"ic? static int Passing9ar=B int Subject9ar=Q:RB boo" fai"B $oid >isp"a#9ar=s() A for (int iM4BiC:B++i) A cout CC19ar=s of subject .o 2B cout CCiCC1is2 CCSubject9ar=QiRB D D $oid Set9ar=s (int 9ar=sQ:R A for (int iM4B iC:B ++i) A Subject9ar=sQiRM9ar=sQiRB D D boo" Chec=Passing() A fai"Mfa"seB for (int iM4BiC:B ++i) A if (Subject9ar=QiRCPassing9ar=) fai"M trueB D if (fai") cout CC 1congratu"ationsS Oou are passingTn2B e"se cout CC1sorr# S Oou are fai"ingTn2B return Sfai"B DDB
int student?? Passing9ar=B ,,reFuired definition $oid main() A student??Passing9ar=M;:B student NB student OB int Nmar=sQRMA5:*::*U:*:U*VWDB int Omar=sQRMA/:*3:*/44*WV*VWDB N Set9ar=s(Nmar=s)B O Set9ar=s(Omar=s)B N Chec=Passing()B O Chec=Passing()B D
D&+a*lt A21*m&nt(
- defau"t argument is a $a"ue gi$en in the +*n'tion -&'la2ation that the compi"er automatica""# inserts if the ca""er does not pro$ide a $a"ue for that argument in the +*n'tion 'all5 S#nta'? return_type f(@! type # & default_value!@);
(unction o$er"oading
(unction redefined &ith different set of arguments EN? add(f"oat* f"oat) -dd(int* int) -dd (int* int* int) (unction o$er"oading is usefu" &hen simi"ar function is reFuired to be ca""ed &ith either $ariab"e number of arguments or arguments of different t#pe or both
#*n'tion O:&2loa-in1
T&o or more functions can ha$e the same name but different parameters E'amp"e?
int ma#(int a! int b) { if (a?& b) return a; else return b; } float ma#(float a! float b) { if (a?& b) return a; else return b; }
8,at i( a #2i&n- #*n'tion; - friend function is used for accessing the non-pub"ic members of a c"ass - c"ass can a""o& non-member functions and other c"asses to access its o&n pri$ate data* b# ma=ing them friends Thus* a friend function is an ordinar# function or a member of another c"ass <o3 to -&+in& an- *(& #2i&n- #*n'tion in C==: The friend function is &ritten as an# other norma" function* e'cept the function dec"aration of these functions is preceded &ith the =e#&ord friend The friend function must ha$e the c"ass to &hich it is dec"ared as friend passed to it in argument Som& im)o2tant )oint( The =e#&ord friend is p"aced on"# in the function dec"aration of the friend function and not in the function definition It is possib"e to dec"are a function as friend in an# number of c"asses <hen a c"ass is dec"ared as a friend* the friend c"ass has access to the pri$ate data of the c"ass that made this a friend It is possib"e to dec"are the friend function as either pri$ate or pub"ic The function can be in$o=ed &ithout the use of an object
c"ass c"ass/ A pri$ate? int numB pub"ic? $oid get() A coutCC@.umber?@B cinXXnumB D friend $oid disp"a#(c"ass/ c")B DB $oid disp"a#(c"ass/ c/) A coutCCC/ .)9B D int main() A c"ass/ c"sB c"s get()B disp"a#(c"s)B D
(riend function
,,static member friend function matri' mu"tip"ication Y Zinc"udeCiostream hX Zinc"udeCconio hX Y c"ass matri'$ector A static int aQ;RQ;RB static int bQ;RB static int cQ;RB pub"ic? $oid getmatri'($oid)B $oid get$ector($oid)B friend int mu"tip"#(matri'$ector m$) DB Y int matri'$ector??aQ;RQ;RB int matri'$ector??bQ;RB int matri'$ector??cQ;RB Y $oid matri'$ector??getmatri'($oid) A coutCC@Tn enter the matri' $a"ue Tn@B for(int iM4BiC;Bi++) A for(int jM4BjC;Bj++) A cinXXaQiRQjRB D D D
$oid matri'$ector??get$ector($oid) A coutCC@Tn@B coutCC@Tn enter the $ector ?@B for(int =M4B =C;B=++) A cinXXbQ=RB D D Y int mu"tip"#(matri'$ector m$) A coutCC@matri' - $ector mu"tip"ication Tn@B coutCC@Tn the $ector Tn@B Y for(int mM4BmC;Bm++) A coutCC@Tn@B coutCCm$ bQmRB D Y coutCC@Tn the matri' Tn@B Y for(int iM4BiC;Bi++) A for (int jM4B jC;B j++) A coutCCm$ aQiRQjRB coutCC@Tt@B D
coutCC@Tn@B D for(int eM4BeC;Be++) A for(int dM4BdC;Bd++) A m$ cQeRMm$ cQeR+m$ aQeRQdR[m$ bQdRB DD coutCC@Tn the resu"t is Tn@B for(int nM4BnC;Bn++) A coutCCm$ cQnRB coutCC@Tn@B D return 4B D Yint main() A c"rscr()B matri'$ector m$B m$ get$ector()B m$ getmatri'()B mu"tip"#(m$)B getch()B return 4BD
$oid Print>etai"s()const A cout CCro""noB cout CCnameB cout CC addressB ro""noM6 ,,error D If ro""no definition is changed to m*ta$l& int ro""noB in the student c"ass *then there &i"" not be an error
\o"ati"e functions
- member function in$o=ed b# a $o"ati"e object - $o"ati"e object ]s $a"ue can be changed b# e'terna" parameters &hich are not under the contro" of the program
:olatil& m&m$&2 +*n'tion( >ec"are a member function &ith the $o"ati"e specifier to ensure that it can be ca""ed safe"# for a $o"ati"e object? c"ass 0 A int 'B pub"ic? $oid f() $o"ati"eB ,, $o"ati"e member function DB int main() A $o"ati"e 0 bB ,, b is a $o"ati"e object b f()B ,, ca"" a $o"ati"e member function safe"# D The object b is dec"ared $o"ati"e Ca""ing a non-$o"ati"e member function from this object is unsafe* because b^s state might ha$e been changed b# a different thread in the meantime To ensure that f() can be ca""ed safe"# for a $o"ati"e object* it^s
p 10 x
<hat is a pointerI
int x = 10; int *p; p = &x; *p = 20; *p is the value at the address p+
p 20 x
<hat is a pointerI
int x = 10; int *p = NULL; p = &x; *p = 20; * dereference operator ets value at p 1eclares a pointer to an inte er & is address operator ets address of #
// !ree t"e memory #elete p; (or e$er# ca"" to new* there must be e'act"# one ca"" to #elete
A )oint&2 'an )oint to an o$%&'t '2&at&- $4 a 'la((5 O$%&'t )oint&2( a2& *(&+*l in '2&atin1 o$%&'t( at 2*n tim&5 student s/B student [ptr M &s/B s/ getdata()B s/ sho&()B eFui$a"ent to ptr-Xgetdata()B ptr-X sho&()B or ([ptr) sho&()B &e can a"so create the objects using pointers and ne& operator student [ptr M ne& studentB This a""ocates enough memor# for the data members in the object structure and assigns the address of the memor# space to ptr
constant objects
const student s/('*#)B ,, object s/ is constant -n# attempt to modif# the $a"ues of ' and # &i"" generate compi"e time error - constant object can ca"" on"# constant member functions $oid Print>etai"s()const A cout CCro""noB cout CCnameB cout CC addressB D
nested c"asses
It is an another &a# of inheriting properties of one c"ass into another (rom this &e can understand that an object can be co""ection of man# other objects* that is a c"ass can contain objects of other c"asses as its members c"ass a"pha(L)B c"ass beta(L)B c"ass gamma A a"pha a/B beta b/B DB -"" objects of gamma c"ass &i"" contain the objects a/ and b/ This =ind of re"ationship is ca""ed
"oca" c"asses
C"asses can be defined and used inside a function or a b"oc= Such c"asses are ca""ed "oca" c"asses $oid test(int a) ,,function A L c"ass student ,,"oca" c"ass A L ,,c"ass definition L DB L L student s/(a)B ,,create student object L L D 7oca" c"asses can use g"oba" $ariab"es and static $ariab"es dec"ared inside the function Enc"osing function cannot access the pri$ate member of a "oca" c"ass