980 likes | 1.12k Views
CS 215-401 Fall 2014. Lecture 11 Class Review, Inheritance, Polymorphism Ismail Abumuhfouz. Slide modified from Link 1. Programming Concept Evolution. Unstructured Procedural Object-Oriented. Procedural Concept.
E N D
CS 215-401 Fall 2014 Lecture 11 Class Review, Inheritance, Polymorphism Ismail Abumuhfouz Slide modified from Link 1
Programming Concept Evolution • Unstructured • Procedural • Object-Oriented
Procedural Concept • The main program coordinates calls to procedures and hands over appropriate data as parameters.
Object-Oriented Concept • Objects of the program interact by sending messages to each other
Objects An object is an encapsulation of both functions and data • 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 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 • 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
OO Perspective Let's look at the Rectangle through object oriented eyes: • Define a new type Rectangle (a class) • Data • width, length • Function • area() • Create an instance of the class (an object) • Request the object for its area In C++, rather than writing a procedure, we define a class that encapsulates the knowledge necessary to answer the question - here, what is the area of the rectangle.
Example Object Oriented Code int area() { return width*length; } }; class Rectangle { private: int width, length; public: Rectangle(int w, int l) { width = w; length = l; } main() { Rectangle rect(3, 5); cout <<rect.area()<<endl; }
Object-Oriented Programming Languages • Characteristics of OOPL: • Encapsulation • Inheritance • Polymorphism • Overloading • OOPLs support : • Modular Programming • Ease of Development • Maintainability
Characteristics of OOPL • Encapsulation: Combining data structure with actions • Data structure: represents the properties, the state, or characteristics of objects • Actions: permissible behaviors that are controlled through the member functions Data hiding: Process of making certain data inaccessible • Inheritance: Ability to derive new objects from oldones • permits objects of a more specific class to inherit the properties (data) and behaviors (functions) of a more general/base class • ability to define a hierarchical relationship between objects • Polymorphism: Ability for different objects to interpret functions differently. • Overloading
VisibilityModifiers Permissions for datamembers andmember functions: ● private:Canonlybeaccessedbythatclass protected:Canbeaccessed bysubclasses public:Canbeaccessed byanyone ● ● ● Classmembers areprivateby default Cannotbeappliedtothewholeclass: ● ● ClassDefinitions
Example class Box { public: // Class name // Public members section // Private members section private: int weight; // Notice the semicolon }; ClassDefinitions
ExampleinUML • Always3 sections • Name • Datamembers • Memberfunctions • Visibilitymodifiers • Public(+) • Private(-) • Protected(#) ● ● ClassDefinitions
InlineMethods Amethodthatisimplementedinsidetheclassdefinitioniscalledaninline method. Thecompilermaychoosetoexpandthebodyofthemethodatthepointofcall. ● ● Thecompiledcodeexecutesfastersinceit avoidstheoverheadofafunction call. Inlining canmakethecompiledcodelargerandmorecomplex(usuallynotdesirableproperties). ● ● Useinlining onlyfor veryshortmethods. Never usethemwithloopsor recursivecalls. ● ●
ClassInterface Usuallytheclass definitionis inaninterface(or header) file,andtheimplementationinan implementation(or source) file. ● Interfacefilesusuallyhavea.hextension. Implementationfilescan havea.cpp,.c++, or.C. Thefilenamedoesnothavetomatchtheclassname. ● ● ● A#includestatementisusedtoincludetheclass definitionintotheimplementationfile: #include “myclass.h” ● ClassDefinitions
FullyQualifiedNames Usea#ifndef...#define...#endifintheheader filetoavoidincludingtheclassdefinitionmorethan once. Methodsimplementedinthesourcefileuseafullyqualifiedfunction name. ● ● Thisavoids conflictswithotherclasses thathaveamethod withthesamename. Afullyqualifiednameconsistsoftheclassname,adoublecolon,andthemethodname: ... ClassName::methodName ... ● ● ClassDefinitions
Example box.c #include “box.h” box.h #ifndef #define ● ● BOX_H BOX_H Box::Box( int w ) { weight = w; } class Box { public: Box( int w ); int Box::getWeight( { return weight; } int getWeight( ) const; ) const private: int weight; }; #endif ClassDefinitions
Constructors Constructors servetwopurposes:theycreateand initializean object Aconstructor isamethodwiththesamenameas theclass, and does nothaveareturntype Therearethreetypesof constructors: ● ● ● Adefaultconstructortakesno arguments Anordinaryconstructorhassomearguments Acopyconstructorisusedtomakecopies(clone) ● ● ● ClassDefinitions
CopyConstructor Acopyconstructor isusedtomakeacopy of an objectvalue. ● Ittakesaninstanceofthesameclassasaconstant referenceargument: Box( const Box & b ); Acopyconstructorisoftencalledimplicitly,suchaswhen passingbyvalue: ● ● a ); // Copy constructor called. doStuff( ClassDefinitions
Example class Box { public: // Default constructor Box( ) { weight = 0; } private: int weight; }; ClassDefinitions
Destructors Thedestructoris implicitlycalledwhenan objectisdeleted ● Objectmayhavebeenexplicitlydeletedusingdelete Anobjectcouldalso beautomaticallydeletedat theendof afunctioniftheobjectisstack-resident Thedestructorisnever calleddirectly ● ● ● Thedestructor isdefined usingatildefollowed by theclassnameandtakesnoarguments: ~Box( ); ● ClassDefinitions
Destructorscont. Thedestructor usuallydeletes any heap-resident memorytheobjectmay haveallocated: class Storage { public: Storage( int s ) { space = new int[s]; } int & operator[]( int i ) { return space[i]; } ~Storage( ) { delete [] space; } private: int * space; ● }; ClassDefinitions
Thekeywordthis Everymethod has apointer namedthiswhich points totheobjectthemethodwasinvoked on class Box { ● public: Box( int w ) : weight( w ) { } Box & doStuff( ) { this->weight = 73; return *this; } private: int weight; }; ClassDefinitions
Friends Aclasscanhavefriends thatareallowedtoaccess itsprivatedatamembers andfunctions: class Box { public: Box( int w ) : weight( w ) { } ● // Allow access for global function operator<< friend ostream & operator<<( ostream & out ); // Allow class Crate to access weight friend class Crate; private: int weight; }; ClassDefinitions
Friend Functions Example #include <iostream> usingnamespacestd; class Rectangle { int width, height; public: Rectangle() {} Rectangle (int x, int y) : width(x), height(y) {} int area() {return width * height;} friend Rectangle duplicate (const Rectangle&); }; Rectangle duplicate (const Rectangle& param) { Rectangle res; res.width = param.width*2; res.height = param.height*2; return res; } int main () { Rectangle foo; Rectangle bar (2,3); foo = duplicate (bar); cout << foo.area() << '\n'; return 0; } Source: http://www.cplusplus.com/doc/tutorial/inheritance/
Friend Class Example #include <iostream> usingnamespacestd; class Square; class Rectangle { int width, height; public: int area () {return (width * height);} void convert (Square a); }; class Square { friendclass Rectangle; private: int side; public: Square (int a) : side(a) {} }; void Rectangle::convert (Square a) { width = a.side; height = a.side; } int main () { Rectangle rect; Square sqr (4); rect.convert(sqr); cout << rect.area(); return 0; } Source: http://www.cplusplus.com/doc/tutorial/inheritance/
More About Friends • In the previous example: • Rectangle is considered a friend class by Square, but Square is not considered a friend by Rectangle. • Therefore, the member functions of Rectangle can access the protected and private members of Square but not the other way around. • Of course, Square could also be declared friend of Rectangle, if needed, granting such an access.Another property of friendships is that they are not transitive: The friend of a friend is not considered a friend unless explicitly specified.
Class Definition • Data Members • Can be of any type, built-in or user-defined • non-static data member • Each class object has its own copy • static data member • Acts as a global variable • One copy per class type, e.g. counter
Static Data Member Rectangle r1; Rectangle r2; Rectangle r3; class Rectangle { private: int width; int length; static int count; public: void set(int w, int l); int area(); } count r1 r2 width length width length width length r3
Static Data Member #include<iostream> usingnamespacestd; classBox{ public: staticintobjectCount; // Constructor definition Box(double l=2.0,double b=2.0,double h=2.0){ cout<<"Constructor called."<<endl; length = l; breadth = b; height = h; // Increase every time object is created objectCount++; } doubleVolume(){ return length * breadth * height; } private: double length;// Length of a box double breadth;// Breadth of a box double height;// Height of a box }; // Initialize static member of class Box intBox::objectCount=0; intmain(void){ BoxBox1(3.3,1.2,1.5);// Declare box1 BoxBox2(8.5,6.0,2.0);// Declare box2 // Print total number of objects. cout<<"Total objects: "<<Box::objectCount<<endl; return0; } Source: http://www.tutorialspoint.com/cplusplus/cpp_static_members.htm
Inheritance Concept class Rectangle{ private: int numVertices; float *xCoord, *yCoord; public: void set(float *x, float *y, int nV); float area(); }; Polygon Rectangle Triangle class Polygon{ private: int numVertices; float *xCoord, *yCoord; public: void set(float *x, float *y, int nV); }; class Triangle{ private: int numVertices; float *xCoord, *yCoord; public: void set(float *x, float *y, int nV); float area(); };
Inheritance Concept class Polygon{ protected: int numVertices; float *xCoord, float *yCoord; public: void set(float *x, float *y, int nV); }; Polygon Rectangle Triangle class Rectangle{ protected: int numVertices; float *xCoord, float *yCoord; public: void set(float *x, float *y, int nV); float area(); }; class Rectangle : public Polygon{ public: float area(); };
Inheritance Concept class Polygon{ protected: int numVertices; float *xCoord, float *yCoord; public: void set(float *x, float *y, int nV); }; Polygon Rectangle Triangle class Triangle{ protected: int numVertices; float *xCoord, float *yCoord; public: void set(float *x, float *y, int nV); float area(); }; class Triangle : public Polygon{ public: float area(); };
Inheritance Concept class Point{ protected: int x, y; public: void set (int a, int b); }; x y Point Circle 3D-Point x y r x y z class Circle : public Point{ private: double r; }; class 3D-Point: public Point{ private: int z; };
Inheritance Concept Augmenting the original class Specializing the original class Polygon Point Rectangle Triangle Circle 3D-Point real imag ComplexNumber ImaginaryNumber RealNumber imag real
Why Inheritance ? • Inheritance is a mechanism for • building class types from existing class types • defining new class types to be a • specialization • augmentation • of existing types
Define a Class Hierarchy • Syntax: classDerivedClassName : access-levelBaseClassName where • access-level specifies the type of derivation • private by default, or • public • Any class can serve as a base class • Thus a derived class can also be a base class
Class Derivation Point class Point{ protected: int x, y; public: void set (int a, int b); }; 3D-Point Sphere class 3D-Point : public Point{ private: double z; … … }; class Sphere : public 3D-Point{ private: double r; … … }; Point is the base class of 3D-Point, while 3D-Point is the base class of Sphere
What to inherit? • In principle, every member of a base class is inherited by a derived class • just with different access permission
Two levels of access control over class members class definition inheritance type Access Control Over the Members class Point{ protected: int x, y; public: void set(int a, int b); }; class Circle : public Point{ … … };
Access Rights of Derived Classes Type of Inheritance The type of inheritance defines the access level for the members of derived classthat are inherited from the base class Access Control for Members
Class Derivation class mother{ protected: int mProc; public: int mPubl; private: int mPriv; }; class grandDaughter : public daughter { private: double gPriv; public: void gFoo ( ); }; private/protected/public int main() { /*….*/ } class daughter : --------- mother{ private: double dPriv; public: void mFoo ( ); }; class daughter : --------- mother{ private: double dPriv; public: void dFoo ( ); }; void daughter :: dFoo ( ){ mPriv = 10; //error mProc = 20; };
What to inherit? • In principle, every member of a base class is inherited by a derived class • just with different access permission • However, there are exceptions for • constructor and destructor • operator=() member • friends Since all these functions are class-specific
Constructor Rules for Derived Classes The default constructor and the destructor of the base class are always called when a new object of a derived class is created or destroyed. class A { public: A ( ) {cout<< “A:default”<<endl;} A (int a) {cout<<“A:parameter”<<endl;} }; class B : public A { public: B (int a) {cout<<“B”<<endl;} }; output: A:default B B test(1);
Constructor Rules for Derived Classes You can also specify an constructor of the base class other than the default constructor • DerivedClassCon ( derivedClass args ) : BaseClassCon ( baseClass args ) • { DerivedClass constructor body } class A { public: A ( ) {cout<< “A:default”<<endl;} A (int a) {cout<<“A:parameter”<<endl;} }; class C : public A { public: C (int a) : A(a) {cout<<“C”<<endl;} }; output: A:parameter C C test(1);
Define its Own Members class Point{ protected: int x, y; public: void set(int a, int b); }; The derived class can also define its own members, in addition to the members inherited from the base class x y Point x y r class Circle{ protected: int x, y; private: double r; public: void set(int a, int b); void set_r(double c); }; Circle class Circle : public Point{ private: double r; public: void set_r(double c); };
Even more … • A derived class can override methods defined in its parent class. With overriding, • the method in the subclass has the identical signature to the method in the base class. • a subclass implements its own version of a base class method. class A { protected: int x, y; public: void print () {cout<<“From A”<<endl;} }; class B : public A { public: void print () {cout<<“From B”<<endl;} };
Access a Method class Point{ protected: int x, y; public: void set(int a, int b) {x=a; y=b;} void foo (); void print(); }; class Circle : public Point{ private: double r; public: void set (int a, int b, double c) { Point :: set(a, b); //same name function call r = c; } void print(); }; Circle C; C.set(10,10,100); // from class Circle C.foo (); // from base class Point C.print(); // from class Circle Point A; A.set(30,50); // from base class Point A.print(); // from base class Point
Time ExtTime Putting Them Together • Time is the base class • ExtTime is the derived class with public inheritance • The derived class can • inherit all members from the base class, except the constructor • access all public and protected members of the base class • define its private data member • provide its own constructor • define its public member functions • override functions inherited from the base class