Date post: | 21-Dec-2015 |
Category: |
Documents |
View: | 215 times |
Download: | 0 times |
11
Object Oriented Object Oriented ProgrammingProgramming
22
What’s the Object?What’s the Object?
Global name space for functions in CGlobal name space for functions in C Every function is available everywhereEvery function is available everywhere
No structural association between No structural association between functions and datafunctions and data
No hiding of private functions or dataNo hiding of private functions or data Code re-use is difficultCode re-use is difficult
33
Object Oriented Programming Object Oriented Programming in C++in C++
Classes as units of encapsulationClasses as units of encapsulation Information HidingInformation Hiding Inheritance Inheritance Polymorphism and dynamic Polymorphism and dynamic
dispatchingdispatching Storage managementStorage management
44
ClassesClasses
Encapsulation of type and related operationsEncapsulation of type and related operationsclassclass point { point { doubledouble x,y; x,y; // private data // private data
membersmembers publicpublic:: point (point (intint x0, x0, intint y0); y0); // public methods// public methods point () { x = 0; y = 0;}; point () { x = 0; y = 0;}; // a constructor// a constructor voidvoid move ( move (intint dx, dx, intint dy); dy); voidvoid rotate ( rotate (doubledouble alpha); alpha); intint distance (point p); distance (point p);}}
55
A Class is a type : Objects are A Class is a type : Objects are instancesinstances
Create a global or local variableCreate a global or local variablepoint p1(10, 20); point p1(10, 20); // Calls constructor point(int x0, int y0)// Calls constructor point(int x0, int y0)point p2; point p2; // Calls default constructor (no // Calls default constructor (no
arguments)arguments)
Create an object on the heapCreate an object on the heappoint p3 = point p3 = newnew point; point;
point is a typepoint is a type p1, p2, p3 are instances of the typep1, p2, p3 are instances of the type p1, p2, p3 are objects p1, p2, p3 are objects
Definitions of Object:Definitions of Object: C++ C++ An An objectobject is a region of storage is a region of storage Java Java An An objectobject is a class instance or array is a class instance or array
66
Implementing methodsImplementing methods Class definition is similar to ADA package spec, Class definition is similar to ADA package spec,
and usually appears in a header fileand usually appears in a header file No equivalent of ADA package body: each No equivalent of ADA package body: each
method can be method can be defineddefined separately separately voidvoid point::rotate ( point::rotate (doubledouble alpha) { alpha) { x = x * cos (alpha) - y * sin (alpha);x = x * cos (alpha) - y * sin (alpha); y = y * cos (alpha) + x * cos (alpha);y = y * cos (alpha) + x * cos (alpha); };};
xx and and yy are data members of the object on are data members of the object on which thewhich the method is being called.method is being called.
Methods can be Methods can be inlinedinlined Must be defined in the class declarationMust be defined in the class declaration ““inline” keyword is a suggestion for the compilerinline” keyword is a suggestion for the compiler
77
ConstructorsConstructors One of the best innovations of C++One of the best innovations of C++ Special method (s) invoked automatically when Special method (s) invoked automatically when
an object of the class is declaredan object of the class is declared point (point (intint x1, x1, intint x2); x2); point ();point ();
point (point (doubledouble alpha; alpha; doubledouble r); r); point p1 (10,10), p2; p3 (pi / 4, 2.5);point p1 (10,10), p2; p3 (pi / 4, 2.5); Allows initialization of instanceAllows initialization of instance
Setting default valuesSetting default values Initializing data structures Initializing data structures
Name of method is name of className of method is name of class Declaration has no return type.Declaration has no return type.
88
Class MethodsClass Methods
Member functions are called with a special syntaxMember functions are called with a special syntaxp1.move(3, -12); p1.move(3, -12); // p1 is an instance of class point// p1 is an instance of class point
Method Name Mangling Method Name Mangling point_move$i$i_v(point* this, int x0, int y0)point_move$i$i_v(point* this, int x0, int y0) Name includes class name and types of argumentsName includes class name and types of arguments Resolves identically named methods in different classesResolves identically named methods in different classes Allows overloading of names within a classAllows overloading of names within a class Allows linking with programs written in C and other Allows linking with programs written in C and other
languageslanguages
And the instance is passed as a hidden argumentAnd the instance is passed as a hidden argumentpoint_move$i$i_v(p1, 3, -12)point_move$i$i_v(p1, 3, -12)
99
Target of operationTarget of operation The implicit parameter in a method call can The implicit parameter in a method call can
be retrieved through be retrieved through thisthis:: classclass Collection { Collection { Collection& insert (thing x) { Collection& insert (thing x) { // return // return
referencereference … … modify data structuremodify data structure returnreturn * *thisthis; ; // to modified // to modified
objectobject };}; };}; my_collection.insert (x1).insert (x2);my_collection.insert (x1).insert (x2);
Common Java IdiomCommon Java Idiom point (int x0, y0) {point (int x0, y0) { this.x0 = x0;this.x0 = x0; this.y0 = y0;}this.y0 = y0;}
1010
Static MembersStatic Members
Need to have computable attributes for class Need to have computable attributes for class itself, independent of specific object; e.g. number itself, independent of specific object; e.g. number of objects created.of objects created.
Static qualifier indicates that entity is Static qualifier indicates that entity is uniqueunique for for the class – There is only one, shared by all class the class – There is only one, shared by all class instances.instances.
staticstatic intint num_objects = 0; num_objects = 0; point () { num_objects++;}; point () { num_objects++;}; // ditto for other // ditto for other
constructorsconstructors Can access static data using Can access static data using class nameclass name or or object object
name:name: ifif ( (pointpoint.num_objects != .num_objects != p1p1.num_objects) error ();.num_objects) error ();
1111
Classes and Private TypesClasses and Private Types
If all data members are private, class is identical to If all data members are private, class is identical to a private type: visible methods, including a private type: visible methods, including assignment.assignment. A A structstruct is a class with all public members is a class with all public members
How much to reveal is up to programmerHow much to reveal is up to programmer What about private constructors?What about private constructors?
define functions to retrieve (define functions to retrieve (not modifynot modify) private ) private datadata
intint xcoord () { xcoord () { returnreturn x;}; x;}; intint ycoord () { ycoord () { returnreturn y;}; y;};
p2.x = 15; p2.x = 15; // error, data member x is // error, data member x is
privateprivate
1212
DestructorsDestructors If constructor allocates dynamic storage, need to If constructor allocates dynamic storage, need to
reclaim itreclaim it classclass stack { stack { intint* contents; * contents; intint sz; sz; publicpublic:: stack (stack (intint size) { contents = size) { contents = newnew int int [ sz = size];};[ sz = size];}; voidvoid push (); push (); intint pop (); pop (); intint size () { size () { returnreturn sz;}; } sz;}; }
stack my_stack (100); stack my_stack (100); // allocate storage dynamically// allocate storage dynamically // when is // when is my_stack.contentsmy_stack.contents released? released?
1313
Destructors (cont.)Destructors (cont.) User cannot User cannot deallocatedeallocate data if data member is data if data member is
private: system must do itprivate: system must do itstack ( ) {contents = stack ( ) {contents = newnew ContentType[n];}; ContentType[n];}; ~stack ( ) {~stack ( ) {deletedelete[ ] contents;};[ ] contents;};
inventive syntax:inventive syntax: negation of constructor negation of constructor Symmetry of ctor & dtor makes program easier to Symmetry of ctor & dtor makes program easier to
understandunderstand Called: Called:
automaticallyautomatically when object goes out of scope when object goes out of scope indirectlyindirectly by by deletedelete Almost never called explicitlyAlmost never called explicitly
Many uses:Many uses: Linked list maintenanceLinked list maintenance Files: open in constructor, close in destructorFiles: open in constructor, close in destructor
1414
Copy and AssignmentCopy and Assignment
point p3 (10,20);point p3 (10,20); point p5 = p3; point p5 = p3; // componentwise copy// componentwise copy
This can lead to unwanted sharing:This can lead to unwanted sharing: stack stack1 (200);stack stack1 (200); stack stack2 = stack1; stack stack2 = stack1; // stack1.contents // stack1.contents
sharedshared stack2.push (15); stack2.push (15); // stack1 is modified// stack1 is modified
Need to redefine assignment and copyNeed to redefine assignment and copy
1515
Copy ConstructorsCopy Constructors
stack (stack (constconst stack& s) { stack& s) { // reference to existing object// reference to existing object
contents = contents = new int new int [ sz = s.size()];[ sz = s.size()];
forfor ( (intint I = 0; I <sz; I++) contents [I] = s.contents [I]; I = 0; I <sz; I++) contents [I] = s.contents [I];
}}
stack s1 (100);stack s1 (100);
… …
stack s2 = s1; stack s2 = s1; // invokes copy constructor// invokes copy constructor
1616
Redefining AssignmentRedefining Assignment
assignment can also be redefined to avoid unwanted assignment can also be redefined to avoid unwanted sharingsharing
operator returns a reference, so it can be used efficiently in operator returns a reference, so it can be used efficiently in chained assignments: chained assignments: one = two = threeone = two = three;;
stack & stack & operatoroperator= (= (constconst stack& s) { stack& s) { ifif ( (thisthis != &s) { != &s) { // beware of self-// beware of self-
assignmentassignment deletedelete [] contents; [] contents; // discard old value// discard old value contents = contents = newnew intint [sz = s.size ()]; [sz = s.size ()]; forfor ( (intint I = 0; I <sz; I++) contents [I] = s.contents [I]; I = 0; I <sz; I++) contents [I] = s.contents [I]; }} returnreturn * *thisthis; }; } stack s1 (100), s2 (200); … s1 = s2; stack s1 (100), s2 (200); … s1 = s2; // transfer // transfer
contentscontents
1717
Operator Overloading: indexingOperator Overloading: indexing
Useful to create range-checked structures:Useful to create range-checked structures:
classclass four_vect { four_vect {
doubledouble stor[4]; stor[4]; // private member, actual contents of // private member, actual contents of vector.vector.
… …
double&double& operatoroperator[ ] ([ ] (intint j) { j) {
if (j < 0 || I > 3) if (j < 0 || I > 3) throwthrow index_error; index_error; // defined elsewhere// defined elsewhere
returnreturn stor[j]; stor[j];
};};
Note: return type is a reference, so can be used on l.h.sNote: return type is a reference, so can be used on l.h.s
1818
Extending the meaning of Extending the meaning of subscriptingsubscripting
An associative array:An associative array:classclass Assoc { Assoc { // a map from strings to // a map from strings to
numbersnumbers
structstruct Pair { Pair { // an inner class// an inner class
charchar* name;* name;
doubledouble val; val;
Pair (Pair (charchar* n = “”, * n = “”, doubledouble v = 0): name (n), val (v) { }; }; v = 0): name (n), val (v) { }; };
pair * contents; pair * contents; // Assoc is a set of pairs// Assoc is a set of pairs
publicpublic::
Assoc () { }; Assoc () { }; // default constructor// default constructor
doubledouble& & operatoroperator[ ] ([ ] (constconst char char *); *); // map string => number// map string => number
};};
1919
Efficiency vs. privacyEfficiency vs. privacy
Linear algebra package: Linear algebra package: vectorvector class for 4- class for 4-vectors, vectors, matrixmatrix class for 4-by-4 matrices class for 4-by-4 matrices
vector class redefines [ ] to do check indexvector class redefines [ ] to do check index matrix class redefines [ ] to check both indicesmatrix class redefines [ ] to check both indices want to implement matrix * vector:want to implement matrix * vector: v1 [j] =v1 [j] = m[j][k] * v [k]; m[j][k] * v [k]; 4 range-checks for every component, all 4 range-checks for every component, all
redundantredundant..
2020
Relaxing privacy: friendsRelaxing privacy: friends A A friendfriend function can access function can access private membersprivate members of a class of a class a friend is declared in the class (a friend is declared in the class (cannot sneak incannot sneak in)) classclass vector {... vector {... friendfriend vector vector operatoroperator* (* (constconst matrix&, matrix&, constconst
vector&);vector&); a function can be the friend of several classesa function can be the friend of several classes
classclass matrix {… matrix {… friendfriend vector vector operatoroperator*(*(constconst matrix&, matrix&, constconst
vector&);vector&); A class can be a friend, so all its function members are.A class can be a friend, so all its function members are. classclass quaternion { quaternion { friendfriend classclass matrix; …} matrix; …}
A friend in not a class memberA friend in not a class member
2121
Efficient codeEfficient code
classclass matrix { vector row [4]; matrix { vector row [4]; publicpublic: … };: … };
vector vector operatoroperator * ( * (constconst matrix&m, matrix&m, constconst vector v) { vector v) {
vector res;vector res;
forfor ( (intint i = 0; i < 4; i ++) { i = 0; i < 4; i ++) {
resres.stor[i] = 0; .stor[i] = 0; // // storstor is private data in a vector is private data in a vector
forfor ( (intint j = 0; j < 4; j++) j = 0; j < 4; j++)
res.stor[j] += m.row[i].stor[j] * v.stor[j]; res.stor[j] += m.row[i].stor[j] * v.stor[j]; // // rowrow is is privateprivate
};};
returnreturn res; res;
};};
2222
Packages and private Packages and private informationinformation
In Ada, declare both types in same package. In Ada, declare both types in same package. Package body has access to full declarations for Package body has access to full declarations for both:both:
packagepackage linear_algebra linear_algebra isis
type vector type vector is privateis private;;
typetype matrix matrix is privateis private;;
functionfunction “*” (m : matrix; v : vector) “*” (m : matrix; v : vector) returnreturn vector; vector;
privateprivate
typetype vector vector is arrayis array (1..4) (1..4) ofof long_float; long_float;
typetype matrix matrix is arrayis array (1..4) (1..4) ofof vector; vector;
-- code in body can use array representation of both.-- code in body can use array representation of both.
endend linear_algebralinear_algebra;;
2323
InheritanceInheritance General mechanism for extending existing General mechanism for extending existing
classes.classes. Specialization: an Specialization: an X is an AX is an A A mammal is a vertebrateA mammal is a vertebrate
a feline is a mammala feline is a mammal a cat is a felinea cat is a feline
a persian is a cat a persian is a cat A A persianpersian has all the attributes of a feline, has all the attributes of a feline,
a mammal, and a vertebratea mammal, and a vertebrate A class hierarchy implements a sequence A class hierarchy implements a sequence
of of Is-AIs-A relations relations
2424
Advantages of inheritanceAdvantages of inheritance
FactorizationFactorization: Common properties are grouped in a : Common properties are grouped in a single classsingle class
code reusecode reuse : Descendant class ( : Descendant class (derived classderived class) is ) is defined incrementally over parent.defined incrementally over parent.
incrementalincremental programmingprogramming : New derived classes : New derived classes can be added without changing existing parents can be added without changing existing parents and siblings.and siblings.
Is inheritance Polymorphism?Is inheritance Polymorphism? Can describe collections of diverse objects belonging to a Can describe collections of diverse objects belonging to a
class hierarchy.class hierarchy. Just saves copying common factors in related classesJust saves copying common factors in related classes
2525
DerivationDerivation classclass point { point { // base class// base class intint x, y; x, y; public:public: point () { x = 0; y = 0}; point () { x = 0; y = 0}; // basic constructor// basic constructor voidvoid move ( move (intint dx, dx, intint dy) { x += dx; y += dy}; } dy) { x += dx; y += dy}; } voidvoid display ( ) ; display ( ) ; // put black dot on the screen.// put black dot on the screen. }} classclass color_point: color_point: publicpublic point { point { // derived class// derived class intint R, G, B; R, G, B; // in addition to hidden members x, // in addition to hidden members x,
yy public:public: color_point ():point () {R = 50; G = 50; B = 50;}; color_point ():point () {R = 50; G = 50; B = 50;}; // call parent // call parent
constrconstr.. voidvoid lighten ( lighten (intint w) { R -= w; G -=w; B -= w;}; w) { R -= w; G -=w; B -= w;}; voidvoid display ( ); display ( ); // put colored dot on the screen// put colored dot on the screen // // movemove is inherited, applies to color_points as well is inherited, applies to color_points as well
};};
2626
Substitution ruleSubstitution rule
An object from a derived class can be used An object from a derived class can be used wherever an object from the base class is expected.wherever an object from the base class is expected.
point* p1 = point* p1 = newnew color_point ( ); color_point ( ); works because a descendant has all the attributes works because a descendant has all the attributes
of the parent (possibly with different meanings).of the parent (possibly with different meanings).
color_point* wrong = color_point* wrong = newnew point ( ); point ( );
// error: incomplete object// error: incomplete object but p1 can be coerced (cast) to a color_point, but p1 can be coerced (cast) to a color_point,
because it is one.because it is one.
2727
inheritance and privacyinheritance and privacy
Private members of the parent class are not Private members of the parent class are not visible in (the methods of) the derived class.visible in (the methods of) the derived class.
intint color_point::abcisa ( ) { color_point::abcisa ( ) {returnreturn x; }; x; }; // error// error
Constructor for parent is used to initialize parent Constructor for parent is used to initialize parent data.data.
Derived (…) : Parent (…) { …}; Derived (…) : Parent (…) { …}; // rest of // rest of constructionconstruction
ProtectedProtected members are visible in descendants, members are visible in descendants, but not outside.but not outside.
2828
PolymorphismPolymorphism
Because of substitution rule, can have collection of various Because of substitution rule, can have collection of various kinds of points:kinds of points:
point* figure [100];point* figure [100]; To display collection, apply the appropriate display method To display collection, apply the appropriate display method
to each:to each:
point::display ()point::display ()
color_point::display ()color_point::display ()
blinkling_point::display ()blinkling_point::display () CouldCould add discriminant to each object, to recognize its class add discriminant to each object, to recognize its class
But don’t do it!But don’t do it! Best to use virtual methodsBest to use virtual methods..
2929
Virtual methodsVirtual methods
classclass parent { parent {
virtual voidvirtual void change ( change (intint x) … x) …
classclass child: child: publicpublic parent { parent {
virtual voidvirtual void change ( change (intint x) … x) … // overrides parent // overrides parent operationoperation
classclass grandchild: grandchild: publicpublic child { child {
virtual voidvirtual void change (int x)… change (int x)… // overrides child // overrides child operationoperation
parent* someone = … parent* someone = … // can be any member of family// can be any member of family
someone-> change () someone-> change () // the proper one for someone’s // the proper one for someone’s classclass
3030
Dynamic dispatchingDynamic dispatching
If M is virtual, the call ptr -> m (..) must If M is virtual, the call ptr -> m (..) must determine the actual nature of determine the actual nature of ptrptr, and invoke , and invoke the proper methodthe proper method
Each class is described by a table of virtual Each class is described by a table of virtual methods (the methods (the vtablevtable))
Each object carries a Each object carries a pointerpointer to the vtable. to the vtable. Each derived class Each derived class inheritsinherits the table the table each each overridingoverriding modifies an entry in the table modifies an entry in the table Dynamic dispatchingDynamic dispatching is an indirect call through an is an indirect call through an
entry at a known position in the vtable.entry at a known position in the vtable.
3131
Overloading and dynamic Overloading and dynamic dispatchingdispatching
Overloading resolution is a Overloading resolution is a compile-timecompile-time process process that applies to an expression in a context:that applies to an expression in a context:
that = this_one + the_other; that = this_one + the_other; // find right numeric // find right numeric typetype
dynamic dispatching is a dynamic dispatching is a run-timerun-time activity that activity that applies to a reference:applies to a reference:
some_relative-> display (); some_relative-> display (); // indirect call// indirect call
tommy.display ();tommy.display (); // static resolution // static resolution overloading resolution overloading resolution may failmay fail if call is ambiguous if call is ambiguous dynamic dispatching succeeds because derived dynamic dispatching succeeds because derived
classes have all the virtual methods of ancestors.classes have all the virtual methods of ancestors.
3232
The profile of an overriding The profile of an overriding methodmethod
classclass parent { parent {
virtual voidvirtual void method ( method (intint x); x);
virtual voidvirtual void relation (parent x); relation (parent x);
classclass child: child: publicpublic parent { parent {
virtual voidvirtual void method ( method (intint x); x); // overrides inherited // overrides inherited methodmethod
virtual voidvirtual void method ( method (doubledouble x); x); // different method// different method
Binary operations are not symmetricBinary operations are not symmetric::
virtual voidvirtual void relation (child x); relation (child x);
// does not override parent // does not override parent relationrelation
virtual voidvirtual void relation (parent x); relation (parent x); // overrides// overrides
3333
Abstract classesAbstract classes
Base class may not have enough attributes to create Base class may not have enough attributes to create meaningful object:meaningful object:
classclass shape { shape {
point anchor;point anchor;
intint color [3]; color [3];
virtual voidvirtual void display (); display (); // can’t write anything // can’t write anything herehere
};};
shape blob; shape blob; // can’t do anything with it// can’t do anything with it If methods are declared abstract, cannot create If methods are declared abstract, cannot create
objects of class:objects of class: virtual voidvirtual void display ( ) = 0; display ( ) = 0; // must be overridden// must be overridden
3434
A useful pattern: the factoryA useful pattern: the factory Need to construct different objects based on run-Need to construct different objects based on run-
time valuestime values Construct objects based on user inputConstruct objects based on user input Handle messages of different typesHandle messages of different types
classclass MessageFactory { MessageFactory {Message messageHandler(byte[] data) {Message messageHandler(byte[] data) {
switch (data[0]) {switch (data[0]) {case 1: return new BuyMessage(data);case 1: return new BuyMessage(data);case 2: return new SellMessage(data);case 2: return new SellMessage(data);case 3: return new case 3: return new
CloseMessage(data);CloseMessage(data);. . .. . .
} } };};
3535
Multiple inheritanceMultiple inheritance Class can inherit from several parents:Class can inherit from several parents:
classclass abstract_stack { abstract_stack { // algebraic definition// algebraic definition
publicpublic::
voidvoid push ( push (intint x) = 0; x) = 0;
......
};};
classclass vector {…}; vector {…}; // sequential allocation// sequential allocation
classclass stack: stack: publicpublic abstract_stack, abstract_stack, publicpublic vector { vector {
publicpublic::
voidvoid push ( push (intint x) { .. }; x) { .. }; // use vector primitives// use vector primitives
}}
Mix-in InheritanceMix-in Inheritance
3636
Multi-methodsMulti-methods
What if we want a function to be dynamically dispatched in What if we want a function to be dynamically dispatched in two dimensions?two dimensions? Shape.render(device) vs. Device.render(shape)Shape.render(device) vs. Device.render(shape) void render(virtual device& d, virtual shape& s);void render(virtual device& d, virtual shape& s); ?????? d.s.render(); ???d.s.render(); ???
Multi-Methods allow multidimensional polymorphismMulti-Methods allow multidimensional polymorphism Dylan supports multi-methodsDylan supports multi-methods Dispatch mechanism must accommodate all possible Dispatch mechanism must accommodate all possible
combinationscombinations Can require dispatch table: Cartesian product of types – very Can require dispatch table: Cartesian product of types – very
expensiveexpensive
Other SolutionsOther Solutions OverloadingOverloading Double dispatch Pattern Double dispatch Pattern
Device::render(Shape& s) { Device::render(Shape& s) { s.render(this); s.render(this); // but shape has to know about different devices// but shape has to know about different devices }}