oops-1
TRANSCRIPT
Object Oriented ProgrammingObject Oriented Programming
Programmer Programmer thinksthinks about and defines the about and defines the attributes and behavior of objects.attributes and behavior of objects.
Often the objects are modeled after real-Often the objects are modeled after real-world entities.world entities.
Very different approach than Very different approach than function-basedfunction-based programming (like C).programming (like C).
Object Oriented ProgrammingObject Oriented Programming
Object-oriented programming (OOP) Object-oriented programming (OOP) – Encapsulates data (attributes) and functions Encapsulates data (attributes) and functions
(behavior) into packages called classes.(behavior) into packages called classes. So, Classes are user-defined (programmer-So, Classes are user-defined (programmer-
defined) types.defined) types.– Data (data members) Data (data members) – Functions (member functions or methods)Functions (member functions or methods)
In other words, they are structures + In other words, they are structures + functionsfunctions
Classes in C++Classes in C++
Member access specifiersMember access specifiers– public: public:
can be accessed outside the class directly.can be accessed outside the class directly.– The public stuff is The public stuff is the interfacethe interface..
– private:private: Accessible only to member functions of classAccessible only to member functions of class Private members and methods are for internalPrivate members and methods are for internal use use
only.only.
class Circle{ private:
double radius; public:
Circle() { radius = 0.0;}Circle(int r);void setRadius(double r){radius = r;}double getDiameter(){ return radius *2;}double getArea();double getCircumference();
};Circle::Circle(int r){ radius = r;}double Circle::getArea(){ return radius * radius * (22.0/7);}double Circle:: getCircumference(){ return 2 * radius * (22.0/7);}
void main(){ Circle c(7); Circle *cp1 = &c; Circle *cp2 = new Circle(7); cout<<“The are of cp2:”
<<cp2->getArea(); }
Another class ExampleAnother class Example
This class shows how to handle time parts.This class shows how to handle time parts.class Time{ private:
int *hour,*minute,*second; public:
Time();Time(int h,int m,int s);void printTime();void setTime(int h,int m,int s);int getHour(){return *hour;}int getMinute(){return *minute;}int getSecond(){return *second;}void setHour(int h){*hour = h;}void setMinute(int m){*minute = m;}void setSecond(int s){*second = s;}~Time();
};
Destructor
Time::Time(){
hour = new int;minute = new int;second = new int;*hour = *minute = *second = 0;
}
Time::Time(int h,int m,int s){
hour = new int;minute = new int;second = new int;*hour = h;*minute = m;*second = s;
}
void Time::setTime(int h,int m,int s){
*hour = h;*minute = m;*second = s;
}
Dynamic locations should be allocated
to pointers first
void Time::printTime(){ cout<<"The time is : ("<<*hour<<":"<<*minute<<":"<<*second<<")"
<<endl;}
Time::~Time(){
delete hour; delete minute;delete second;}
void main(){
Time *t;t= new Time(3,55,54);t->printTime();
t->setHour(7);t->setMinute(17);t->setSecond(43);
t->printTime();
delete t;}
Output:The time is : (3:55:54)The time is : (7:17:43)Press any key to continue
Destructor: used here to de-allocate memory locations
When executed, the destructor is called
Reasons for OOPReasons for OOP
1.1. Simplify programmingSimplify programming
2.2. InterfacesInterfaces Information hiding:Information hiding:
– Implementation details hidden within classes themselvesImplementation details hidden within classes themselves
3.3. Software reuseSoftware reuse Class objects included as members of other Class objects included as members of other
classesclasses
First introduced scope rules for data hidingFirst introduced scope rules for data hiding..Public part consists of variables and Public part consists of variables and
functions that are visible functions that are visible outsideoutside of the of the modulemodule..
Private part consists of variables and Private part consists of variables and functions visible only functions visible only withinwithin the module the module..
Modules may span multiple compilation Modules may span multiple compilation units (files)units (files)..
Modules generally lack any inheritance Modules generally lack any inheritance mechanismmechanism..
Modules
Why OO-ProgrammingWhy OO-Programming??
Reduces Reduces conceptual loadconceptual load by reducing by reducing amount of detailamount of detail
Provides Provides fault containmentfault containment–Can’t use components (e.g., a class) in Can’t use components (e.g., a class) in
inappropriate waysinappropriate ways
Provides Provides independenceindependence between between componentscomponents
–Design/development can be done by more than Design/development can be done by more than one personone person
Global Variables -lifetime spans program Global Variables -lifetime spans program executionexecution..
Local Variables - lifetime limited to execution Local Variables - lifetime limited to execution of a single routineof a single routine..
Nested Scopes - allow functions to be localNested Scopes - allow functions to be local..Static Variables - visible in single scopeStatic Variables - visible in single scope..Modules - allow several subroutines to share Modules - allow several subroutines to share
a set of static variablesa set of static variables..Module Types - multiple instances of an Module Types - multiple instances of an
abstractionabstraction..Classes - families of related abstractionsClasses - families of related abstractions..
The Evolution of OOPS
An instance of a class is know as an An instance of a class is know as an ObjectObject..
Languages that are based on classes are Languages that are based on classes are know as know as Object-OrientedObject-Oriented..
–EiffelEiffel–CC++++–Modula-3Modula-3–Ada 95Ada 95–JavaJava
Keys to OO Programming
Encapsulation (data hiding)Encapsulation (data hiding)–Enable programmer to group data & subroutines Enable programmer to group data & subroutines
(methods) together, hiding irrelevant details from users(methods) together, hiding irrelevant details from users
InheritanceInheritance–Enable a new abstraction (i.e., derived class) to be Enable a new abstraction (i.e., derived class) to be
defined as an extension of an existing abstraction, defined as an extension of an existing abstraction, retaining key characteristicsretaining key characteristics
Dynamic method bindingDynamic method binding–Enable use of new abstraction (i.e., derived class) to Enable use of new abstraction (i.e., derived class) to
exhibit new behavior in context of old abstractionexhibit new behavior in context of old abstraction
Keys to OO Programming
Classes in C++Classes in C++
A class definition begins with the keyword A class definition begins with the keyword classclass..
The body of the class is contained within a The body of the class is contained within a set of braces, set of braces, { } ;{ } ; (notice the semi-colon). (notice the semi-colon).
class class_name}.….….…;{
Class body (data member + methodsmethods)
Any valid identifier
Classes in CClasses in C++++
Within the body, the keywords Within the body, the keywords private:private: and and public:public: specify the access level of the specify the access level of the members of the class.members of the class.– the default is the default is privateprivate..
Usually, the data members of a class are Usually, the data members of a class are declared in the declared in the private:private: section of the class section of the class and the member functions are in and the member functions are in public:public: section.section.
Classes in C++Classes in C++
class class_name}
private:………
public:………
;{
Public members or methods
private members or methods
Class ExampleClass Example
This class example shows how we can This class example shows how we can encapsulate (gather) a circle information into encapsulate (gather) a circle information into one package (unit or class) one package (unit or class)
class Circle{ private:
double radius; public:
void setRadius(double r);double getDiameter();
double getArea();double getCircumference();
};
No need for others classes to access and retrieve its value directly. Theclass methods are responsible forthat only.
They are accessible from outsidethe class, and they can access themember (radius)
Creating an object of a ClassCreating an object of a Class
Declaring a variable of a class type creates an Declaring a variable of a class type creates an objectobject. You can have many variables of the same . You can have many variables of the same type (class).type (class).– InstantiationInstantiation
Once an object of a certain class is instantiated, a Once an object of a certain class is instantiated, a new memory location is created for it to store its new memory location is created for it to store its data members and codedata members and code
You can instantiate many objects from a class You can instantiate many objects from a class type.type.– Ex) Circle c; Circle *c; Ex) Circle c; Circle *c;
Special Member FunctionsSpecial Member Functions
Constructor:Constructor:– Public function memberPublic function member– called when a new object is created called when a new object is created
(instantiated).(instantiated).– Initialize data members.Initialize data members.– Same name as classSame name as class– No return typeNo return type– Several constructorsSeveral constructors
Function overloadingFunction overloading
Special Member FunctionsSpecial Member Functions
class Circle{ private:
double radius; public:
Circle();Circle(int r); void setRadius(double r);double getDiameter();double getArea();double getCircumference();
};
Constructor with no argument
Constructor with one argument
Implementing class methodsImplementing class methods
Class implementation: writing the code of class Class implementation: writing the code of class methods.methods.
There are two ways:There are two ways:1.1. Member functions defined outside classMember functions defined outside class
Using Binary scope resolution operator (Using Binary scope resolution operator (::::)) ““Ties” member name to class nameTies” member name to class name Uniquely identify functions of particular classUniquely identify functions of particular class Different classes can have member functions with same Different classes can have member functions with same
namename– Format for defining member functionsFormat for defining member functions
ReturnTypeReturnType ClassNameClassName::::MemberFunctionNameMemberFunctionName( ){( ){……
}}
Implementing class methodsImplementing class methods
2.2. Member functions defined inside classMember functions defined inside class– Do not need scope resolution operator, class Do not need scope resolution operator, class
name;name;class Circle{ private:
double radius; public:
Circle() { radius = 0.0;}Circle(int r);void setRadius(double r){radius = r;}double getDiameter(){ return radius *2;}double getArea();double getCircumference();
};
Defined inside class
class Circle{ private:
double radius; public:
Circle() { radius = 0.0;}Circle(int r);void setRadius(double r){radius = r;}double getDiameter(){ return radius *2;}double getArea();double getCircumference();
};Circle::Circle(int r){ radius = r;}double Circle::getArea(){ return radius * radius * (22.0/7);}double Circle:: getCircumference(){ return 2 * radius * (22.0/7);}
Defined outside class
Accessing Class MembersAccessing Class Members
Operators to access class membersOperators to access class members– Identical to those for Identical to those for structstructss– Dot member selection operator (Dot member selection operator (..))
ObjectObject Reference to objectReference to object
– Arrow member selection operator (Arrow member selection operator (->->) ) PointersPointers
class Circle{ private:
double radius; public:
Circle() { radius = 0.0;}Circle(int r);void setRadius(double r){radius = r;}double getDiameter(){ return radius *2;}double getArea();double getCircumference();
};Circle::Circle(int r){ radius = r;}double Circle::getArea(){ return radius * radius * (22.0/7);}double Circle:: getCircumference(){ return 2 * radius * (22.0/7);}
void main(){ Circle c1,c2(7);
cout<<“The area of c1:” <<c1.getArea()<<“\n”;
//c1.raduis = 5;//syntax error c1.setRadius(5);
cout<<“The circumference of c1:”<< c1.getCircumference()<<“\n”;
cout<<“The Diameter of c2:”<<c2.getDiameter()<<“\n”;
}
The first constructor is
called
The second constructor is
called
Since radius is a private class data
member
ClassesClasses
Extends the scope rules of modules to Extends the scope rules of modules to include inheritanceinclude inheritance..
Should private members of a base class be Should private members of a base class be visible in derived classesvisible in derived classes??
Should public members of a base class Should public members of a base class always be public members of a derived always be public members of a derived
classclass..How much control should a base class How much control should a base class
have over its members in derived classeshave over its members in derived classes??
C++ ClassesC++ Classes
Any class can limit the visibility of its Any class can limit the visibility of its membersmembers::
–PublicPublic members are visible anywhere the class members are visible anywhere the class is in scopeis in scope..
–PrivatePrivate members are visible only within the members are visible only within the class’s methodsclass’s methods..
–ProtectedProtected members are visible inside members members are visible inside members of the class and derived classesof the class and derived classes..
–FriendFriend classes are granted exceptions to classes are granted exceptions to (some) of the rules(some) of the rules..
C++ ClassesC++ Classes
Derived classes can further restrict visibility of Derived classes can further restrict visibility of base class members, but not increase itbase class members, but not increase it::
–Private members of a base class are never visible in a Private members of a base class are never visible in a derived classderived class..
–Protected and public members of a public base class Protected and public members of a public base class are protected or public, respectively, in a derived classare protected or public, respectively, in a derived class..
–Protected and public members of a protected base Protected and public members of a protected base class are protected members of a derived classclass are protected members of a derived class..
–Protected and public members of a private base class Protected and public members of a private base class are private members of a derived classare private members of a derived class..
C++ ClassesC++ Classes
Derived classes that limit visibility of base class Derived classes that limit visibility of base class members can restore visibility by inserting a members can restore visibility by inserting a
using declaration in its protected or public using declaration in its protected or public sectionssections..
Rules in other languages can be significantly Rules in other languages can be significantly differentdifferent..
EncapsulationEncapsulation
Encapsulation Requires that functions, modules and classesEncapsulation Requires that functions, modules and classes::–Have clearly defined external interfacesHave clearly defined external interfaces–Hide implementation detailsHide implementation details
Encapsulation is all about coupling – coupling happens Encapsulation is all about coupling – coupling happens through interfacesthrough interfaces..
Exactly what is an interfaceExactly what is an interface??
private data
private functions
public functions
Abstract Data TypesAbstract Data Types
ModularityModularity–Keeps the complexity of a large program Keeps the complexity of a large program
manageable by systematically controlling manageable by systematically controlling the interaction of its componentsthe interaction of its components
–Isolates errorsIsolates errors
Abstract Data TypesAbstract Data Types
Modularity (Continued)Modularity (Continued)–Eliminates redundanciesEliminates redundancies–A modular program isA modular program is
Easier to writeEasier to writeEasier to readEasier to readEasier to modifyEasier to modify
Abstract Data TypesAbstract Data Types
Procedural abstractionProcedural abstraction–Separates the purpose and use of a module Separates the purpose and use of a module
from its implementationfrom its implementation–A module’s specifications shouldA module’s specifications should
Detail how the module behavesDetail how the module behavesIdentify details that can be hidden within the moduleIdentify details that can be hidden within the module
Abstract Data TypesAbstract Data Types
Information hidingInformation hiding–Hides certain implementation details within a Hides certain implementation details within a
modulemodule–Makes these details inaccessible from outside Makes these details inaccessible from outside
the modulethe module
Abstract Data TypesAbstract Data Types
Figure 3.1
Isolated tasks: the implementation of task T does not affect task Q
Abstract Data TypesAbstract Data Types
The isolation of modules is not totalThe isolation of modules is not total–Functions’ specifications, or contracts, govern how they interact Functions’ specifications, or contracts, govern how they interact
with each otherwith each other
Figure 3.2 A slit in the wall
Abstract Data TypesAbstract Data Types
Typical operations on dataTypical operations on data–Add data to a data collectionAdd data to a data collection–Remove data from a data collectionRemove data from a data collection–Ask questions about the data in a data Ask questions about the data in a data
collectioncollection
Abstract Data TypesAbstract Data Types
Data abstractionData abstraction–Asks you to think Asks you to think whatwhat you can do to a you can do to a
collection of data independently of collection of data independently of howhow you do it you do it–Allows you to develop each data structure in Allows you to develop each data structure in
relative isolation from the rest of the solutionrelative isolation from the rest of the solution–A natural extension of procedural abstractionA natural extension of procedural abstraction
Abstract Data TypesAbstract Data Types
Abstract data type (ADT)Abstract data type (ADT)–An ADT is composed ofAn ADT is composed of
A collection of dataA collection of dataA set of operations on that dataA set of operations on that data
–Specifications of an ADT indicateSpecifications of an ADT indicateWhat the ADT operations do, not how to implement What the ADT operations do, not how to implement
themthem
–Implementation of an ADTImplementation of an ADTIncludes choosing a particular data structureIncludes choosing a particular data structure
Abstract Data TypesAbstract Data Types
Figure 3.4
A wall of ADT operations isolates a data structure from the program that uses it
The ADT ListThe ADT List
Except for the first and last items, each item Except for the first and last items, each item has a unique predecessor and a unique has a unique predecessor and a unique
successorsuccessorHead or front do not have a predecessorHead or front do not have a predecessorTail or end do not have a successorTail or end do not have a successor
The ADT ListThe ADT List
Items are referenced by their position within Items are referenced by their position within the listthe list
Specifications of the ADT operationsSpecifications of the ADT operations–Define the contract for the ADT listDefine the contract for the ADT list–Do not specify how to store the list or how to Do not specify how to store the list or how to
perform the operationsperform the operationsADT operations can be used in an ADT operations can be used in an
application without the knowledge of how application without the knowledge of how the operations will be implementedthe operations will be implemented
The ADT ListThe ADT List
ADT List operationsADT List operations–Create an empty listCreate an empty list–Determine whether a list is emptyDetermine whether a list is empty–Determine the number of items in a listDetermine the number of items in a list–Add an item at a given position in the listAdd an item at a given position in the list–Remove the item at a given position in the listRemove the item at a given position in the list–Remove all the items from the listRemove all the items from the list–Retrieve (get) item at a given position in the listRetrieve (get) item at a given position in the list
The ADT ListThe ADT List
The ADT sorted listThe ADT sorted list–Maintains items in sorted orderMaintains items in sorted order–Inserts and deletes items by their values, not Inserts and deletes items by their values, not
their positionstheir positions
The ADT ListThe ADT List
Figure 3.7
The wall between displayList and the implementation of the ADT list
Designing an ADTDesigning an ADT
The design of an ADT should evolve The design of an ADT should evolve naturally during the problem-solving processnaturally during the problem-solving process
Questions to ask when designing an ADTQuestions to ask when designing an ADT–What data does a problem requireWhat data does a problem require??–What operations does a problem requireWhat operations does a problem require??
Designing an ADTDesigning an ADT
For complex abstract data types, the For complex abstract data types, the behavior of the operations must be specified behavior of the operations must be specified
using axiomsusing axioms–Axiom: A mathematical ruleAxiom: A mathematical rule–Ex. : (aList.createList()).size() = 0Ex. : (aList.createList()).size() = 0
Implementing ADTsImplementing ADTs
Choosing the data structure to represent the Choosing the data structure to represent the ADT’s data is a part of implementationADT’s data is a part of implementation
–Choice of a data structure depends onChoice of a data structure depends onDetails of the ADT’s operationsDetails of the ADT’s operationsContext in which the operations will be usedContext in which the operations will be used
Implementing ADTsImplementing ADTs
Implementation details should be hidden Implementation details should be hidden behind a wall of ADT operationsbehind a wall of ADT operations
–A program would only be able to access the A program would only be able to access the data structure using the ADT operationsdata structure using the ADT operations
C++ ClassesC++ Classes
Encapsulation combines an ADT’s data with Encapsulation combines an ADT’s data with its operations to form an objectits operations to form an object
–An object is an instance of a classAn object is an instance of a class–A class contains data members and member A class contains data members and member
functionsfunctions
By default, all members in a class are By default, all members in a class are privateprivate
class Rectangleclass Rectangle}}
privateprivate::
int numVerticesint numVertices;;
float *xCoord, *yCoordfloat *xCoord, *yCoord;;
publicpublic::
void set(float *x, float *y, int nV)void set(float *x, float *y, int nV);;
float areafloat area;();()
;{;{
Inheritance ConceptInheritance Concept
Rectangle Triangle
Polygon
class Polygonclass Polygon}}
privateprivate::
int numVerticesint numVertices;;
float *xCoord, *yCoordfloat *xCoord, *yCoord;;
publicpublic::
void set(float *x, float *y, int nV)void set(float *x, float *y, int nV);;
;{;{
class Triangleclass Triangle}}
privateprivate::
int numVerticesint numVertices;;
float *xCoord, *yCoordfloat *xCoord, *yCoord;;
publicpublic::
void set(float *x, float *y, int nV)void set(float *x, float *y, int nV);;
float areafloat area;();()
;{;{
Rectangle Triangle
Polygonclass Polygonclass Polygon}}
protectedprotected::
int numVerticesint numVertices;;
float *xCoord, float *yCoordfloat *xCoord, float *yCoord;;
publicpublic::
void set(float *x, float *y, int nV)void set(float *x, float *y, int nV);;
;{;{
class Rectangle : public class Rectangle : public PolygonPolygon}}
publicpublic::
floatfloat area area;();()
;{;{
class Rectangleclass Rectangle}}
protectedprotected::
int numVerticesint numVertices;;
float *xCoord, float *yCoordfloat *xCoord, float *yCoord;;
publicpublic::
void set(float *x, float *y, int nV)void set(float *x, float *y, int nV);;
float areafloat area;();()
;{;{
Inheritance ConceptInheritance Concept
Rectangle Triangle
Polygonclass Polygonclass Polygon}}
protectedprotected::
int numVerticesint numVertices;;
float *xCoord, float *yCoordfloat *xCoord, float *yCoord;;
publicpublic::
void set(float *x, float *y, int nV)void set(float *x, float *y, int nV);;
;{;{
class Triangle : public class Triangle : public PolygonPolygon}}
publicpublic::
float areafloat area;();()
;{;{
class Triangleclass Triangle}}
protectedprotected::
int numVerticesint numVertices;;
float *xCoord, float *yCoordfloat *xCoord, float *yCoord;;
publicpublic::
void set(float *x, float *y, int nV)void set(float *x, float *y, int nV);;
float areafloat area;();()
;{;{
Inheritance ConceptInheritance Concept
Inheritance ConceptInheritance Concept
Point
Circle 3D-Point
class Pointclass Point}}
protectedprotected::
int x, yint x, y;;
publicpublic::
void set (int a, int b)void set (int a, int b);;
;{;{
class Circle : public Pointclass Circle : public Point}}
privateprivate : :
double rdouble r;;
;{;{
class 3D-Point: public class 3D-Point: public PointPoint}}
privateprivate : :
int zint z;;
;{;{
xy
xyr
xyz
Augmenting the original classAugmenting the original class
Specializing the original classSpecializing the original class
Inheritance ConceptInheritance Concept
RealNumber
ComplexNumber
ImaginaryNumber
Rectangle Triangle
Polygon Point
Circle
realimag
real imag
3D-Point
Why InheritanceWhy Inheritance? ?
Inheritance is a mechanism forInheritance is a mechanism for
building class types from existing class building class types from existing class typestypes
defining new class types to be adefining new class types to be a –specializationspecialization –augmentationaugmentation
of existing typesof existing types
Define a Class HierarchyDefine a Class Hierarchy
SyntaxSyntax::
classclass DerivedClassNameDerivedClassName : : access-levelaccess-level BaseClassNameBaseClassName
wherewhere –access-level access-level specifies the type of derivationspecifies the type of derivation
private by default, orprivate by default, orpublicpublic
Any class can serve as a base classAny class can serve as a base class–Thus a derived class can also be a base classThus a derived class can also be a base class
Class DerivationClass Derivation
Point
3D-Point
class Pointclass Point}}
protectedprotected::
int x, yint x, y;;
publicpublic::
void set (int a, int b)void set (int a, int b);;
;{;{
class 3D-Point : public Pointclass 3D-Point : public Point}}
privateprivate : :
double zdouble z;;
… …… …
;{;{
class Sphere : public 3D-Pointclass Sphere : public 3D-Point}}
privateprivate : :
double rdouble r;;
… …… …
;{;{
Sphere
Point is the base class of 3D-Point, while 3D-Point is the base class of Sphere
What to inheritWhat to inherit??
In principleIn principle, every member of a base class is , every member of a base class is inherited by a derived classinherited by a derived class
– just with different access permissionjust with different access permission
Access Control Over the MembersAccess Control Over the Members
Two levels of access control Two levels of access control over class membersover class members
–class definitionclass definition–inheritance typeinheritance type
base c lass / supe rc lass /pa ren t c lass
deriv ed c lass / subc lass /ch ild c lass
deriv
e fro
m
mem
bers
goe
s to
class Pointclass Point}}
protected:protected: int x, y int x, y;;
public:public: void set(int a, int b) void set(int a, int b);;
;{;{
class Circle : class Circle : publicpublic Point Point}}
… …… …
;{;{
The type of inheritance defines the access level for the The type of inheritance defines the access level for the members of derived classmembers of derived class that are inherited from the that are inherited from the
base classbase class
Access Rights or access Access Rights or access specifiers of Derived Classesspecifiers of Derived Classes
privateprivateprotectedprotectedpublicpublic
privateprivate------
protecteprotectedd
privateprivateprotectedprotectedprotectedprotected
publicpublicprivateprivateprotectedprotectedpublicpublic
Type of Inheritance
Access
Control
for Mem
bers
Public InheritancePublic Inheritance
public base class (B)public base class (B)
public memberspublic members
protected membersprotected members
private membersprivate members
derived class (A)derived class (A)
publicpublic
protectedprotected
inherited but not inherited but not accessibleaccessible
class class AA : public : public BB}} // //Class A now inherits the members of Class Class A now inherits the members of Class
BB // //with no change in the “access specifier” forwith no change in the “access specifier” for
{{ // //the inherited membersthe inherited members
Protected InheritanceProtected Inheritance
protected base class protected base class (B)(B)
public memberspublic members
protected membersprotected members
private membersprivate members
derived class (A)derived class (A)
protectedprotected
protectedprotected
inherited but not inherited but not accessibleaccessible
class class AA : protected : protected BB}} // //Class A now inherits the members of Class Class A now inherits the members of Class
BB // //with with publicpublic members “promoted” to members “promoted” to protectedprotected
{{ // //but no other changes to the inherited but no other changes to the inherited membersmembers
Private InheritancePrivate Inheritance
private base class (B)private base class (B)
public memberspublic members
protected membersprotected members
private membersprivate members
derived class (A)derived class (A)
privateprivate
privateprivate
inherited but not inherited but not accessibleaccessible
class class AA : private : private BB}} // //Class A now inherits the members of Class A now inherits the members of
Class BClass B // //with with publicpublic and and protectedprotected members members
{{“ //“ //promoted” to promoted” to privateprivate
class daughter : class daughter : ------------------ mothermother}}
private: double dPrivprivate: double dPriv;;
public: void mFoopublic: void mFoo;( ) ;( )
;{;{
Class DerivationClass Derivationclass motherclass mother}}
protected: protected: int mProcint mProc;;
public: public: int mPublint mPubl;;
private: private: int mPrivint mPriv;;
;{;{
class daughter : class daughter : ------------------ mothermother}}
private: double dPrivprivate: double dPriv;;
public: void dFoopublic: void dFoo;( ) ;( )
;{;{
void daughter :: dFoovoid daughter :: dFoo}( ) }( )
mPriv = 10;mPriv = 10; //error //error
mProc = 20mProc = 20;;
;{;{
private/protected/publicint mainint main} ()} ()
/*.…*//*.…*/
{{
class grandDaughter : class grandDaughter : publicpublic daughter daughter} }
private: double gPrivprivate: double gPriv;;
public: void gFoopublic: void gFoo;( ) ;( )
;{;{
What to inheritWhat to inherit??
In principleIn principle, every member of a base , every member of a base class is inherited by a derived classclass is inherited by a derived class
– just with different access permissionjust with different access permission
HoweverHowever, there are exceptions for, there are exceptions for–constructor and destructorconstructor and destructor –operator=() memberoperator=() member –friendsfriends
Since all these functions are class-specificSince all these functions are class-specific
Inheritance (continued)Inheritance (continued)classclass Shape Shape }}publicpublic::
intint GetColor GetColor ; ( ); ( ) // //so derived classes can access itso derived classes can access it
protectedprotected:: intint color color;;
;{;{classclass Two_D Two_D :: publicpublic Shape Shape}}
// //put members specific to 2D shapes hereput members specific to 2D shapes here;{;{classclass Three_D Three_D :: publicpublic Shape Shape}}
// //put members specific to 3D shapes hereput members specific to 3D shapes here;{;{
Inheritance (continued)Inheritance (continued)classclass Square Square :: publicpublic Two_D Two_D}}publicpublic::
floatfloat getArea getArea ; ( ); ( )protectedprotected::floatfloat edge_length edge_length;;
; {; {classclass Cube Cube :: publicpublic Three_D Three_D}}publicpublic::
floatfloat getVolume getVolume ; ( ); ( )protectedprotected::floatfloat edge_length edge_length;;
; {; {
Inheritance (continued)Inheritance (continued)int mainint main ( ) ( )
}}
Square mySquareSquare mySquare;;
Cube myCubeCube myCube;;
// // Square inheritsSquare inherits
mySquaremySquare..getColorgetColor ;( );( )
mySquaremySquare..getAreagetArea ;( );( )
// // Cube inherits getColorCube inherits getColor)()(
myCubemyCube..getColorgetColor ;( );( )
myCubemyCube..getVolumegetVolume ;( );( )
{{
Define its Own MembersDefine its Own Members
Point
Circle
class Pointclass Point}}
protectedprotected::
int x, yint x, y;;
publicpublic::
void set(int a, int b)void set(int a, int b);;
;{;{
class Circle : public Pointclass Circle : public Point}}
privateprivate : :
double rdouble r;;
publicpublic::
void set_r(double c)void set_r(double c);;
;{;{
xy
xyr
class Circleclass Circle}}
protectedprotected::
int x, yint x, y;;
privateprivate::
double rdouble r;;
publicpublic::
void set(int a, int b)void set(int a, int b);;
void set_r(double c)void set_r(double c);;
;{;{
The derived class can also define its own members, in addition to the members inherited from the base class
Even moreEven more… …
A derived class can A derived class can overrideoverride methods defined in its methods defined in its
parent class. With overridingparent class. With overriding,, –the method in the subclass has the identical signature to the the method in the subclass has the identical signature to the
method in the base classmethod in the base class . .–a subclass implements its own version of a base class methoda subclass implements its own version of a base class method . .
class Aclass A} }
protectedprotected::
int x, yint x, y;;
publicpublic::
void printvoid print() ()
}}cout<<“From A”<<endlcout<<“From A”<<endl{;{;
;{;{
class B : public Aclass B : public A} }
publicpublic : :
void printvoid print() ()
} } cout<<“From B”<<endlcout<<“From B”<<endl{;{;
;{;{
class Pointclass Point}}
protectedprotected::
int x, yint x, y;;
publicpublic::
void void setset(int a, int b)(int a, int b)
}}x=a; y=bx=a; y=b{;{;
void void foofoo;() ;()
void void printprint;();()
;{;{
class Circle : public Pointclass Circle : public Point}}
private: double rprivate: double r;;
publicpublic::
void void setset (int a, int b, double c) (int a, int b, double c)} }
Point :: set(a, b); Point :: set(a, b); //same name function call//same name function call
r = cr = c;;
{{
void void printprint;{ ;();{ ;()
Access a MethodAccess a Method
Circle CCircle C;;
C.C.setset(10,10,100); // from class Circle(10,10,100); // from class Circle
C.C.foo foo (); // from base class Point(); // from base class Point
C.C.printprint(); // from class Circle(); // from class Circle
Point APoint A;;
A.A.setset(30,50); (30,50); // from base class // from base class PointPoint
A.A.printprint(); (); // from base class Point// from base class Point
Putting Them TogetherPutting Them Together
TimeTime is the base class is the base classExtTimeExtTime is the derived class is the derived class
with public inheritancewith public inheritanceThe derived class canThe derived class can
–inherit all members from the base inherit all members from the base class, except the constructorclass, except the constructor
–access all public and protected access all public and protected members of the base classmembers of the base class
–define its private data memberdefine its private data member–provide its own constructorprovide its own constructor–define its public member define its public member
functionsfunctions–override functions inherited from override functions inherited from
the base classthe base class
ExtTime
Time
Take Home MessageTake Home Message
Inheritance is a mechanism for defining new Inheritance is a mechanism for defining new class types to be a specialization or an class types to be a specialization or an
augmentation of existing typesaugmentation of existing types..
In principle, every member of a base class In principle, every member of a base class is inherited by a derived class with different is inherited by a derived class with different
access permissions, except for the access permissions, except for the constructorsconstructors
Polymorphism:DefinitionPolymorphism:Definition
It is an important feature of OOPsIt is an important feature of OOPs..It simply means one name, multiple formsIt simply means one name, multiple forms..
Types of polymorphismTypes of polymorphism
Primitively divided into two typesPrimitively divided into two typespolymorphism
Run-time polymorphismCompile-time
polymorphism
Operator overloadingFunction Overloading Virtual functions
Compile time polymorphismCompile time polymorphism
Binding of Function call and function Binding of Function call and function definition is done during compile time. This definition is done during compile time. This
is known as is known as static bindingstatic binding..
In In function overloading and operatorfunction overloading and operator overloadingoverloading static binding happens, hence static binding happens, hence they come under compile time they come under compile time
polymorphismpolymorphism..
Run-time polymorphismRun-time polymorphism
Binding of Function call and function Binding of Function call and function definition is done during Run time. This is definition is done during Run time. This is
known as late or known as late or dynamic bindingdynamic binding..If late binding happens in polymorphism it is If late binding happens in polymorphism it is
known as run-time polymorphismknown as run-time polymorphismC++ supports a mechanism known as C++ supports a mechanism known as
virtual functionsvirtual functions to achieve run-time to achieve run-time polymorphismpolymorphism..
ExampleExample::Class personClass person
{{char name[30]char name[30];;
float agefloat age;;publicpublic::
person)char *s,float a(person)char *s,float a({ {
strcpy)name,s(strcpy)name,s(;; age=aage=a;;
} } person& greater)person &x(person& greater)person &x(
{{if)x.age>=age(if)x.age>=age(
return xreturn x;;elseelse
return *thisreturn *this;;} }
void display )void(void display )void({{
cout<<name<<agecout<<name<<age;;}}
;};}
Abstract ClassesAbstract Classes
An abstract class represents an abstract concept in C++ (such An abstract class represents an abstract concept in C++ (such as Shape class)as Shape class)
1. Defines the interfaces that all of the concrete classes (subclasses) share
2. Does not define state and implementation unless it is common to all concrete classes
3. Cannot be instantiated
Shape
Circle Polygon
Rectangle
int mainint main()()}}
Person P1(“john”,32)Person P1(“john”,32);;Person P2(“ahmed”,38)Person P2(“ahmed”,38);;Person P3(“karthik”,30)Person P3(“karthik”,30);;
Person p=P1.greater(P2)Person p=P1.greater(P2);;cout <<“elder personcout <<“elder person;”;”
p.displayp.display;();()p=P3.greater(P2)p=P3.greater(P2);;
cout<<“younger personcout<<“younger person;”;”p.displayp.display;();()
{{
Abstract ClassesAbstract Classes
An abstract class represents an abstract concept in C++ (such An abstract class represents an abstract concept in C++ (such as Shape class)as Shape class)
1. Defines the interfaces that all of the concrete classes (subclasses) share
2. Does not define state and implementation unless it is common to all concrete classes
3. Cannot be instantiated
Shape
Circle Polygon
Rectangle
Function OverloadingFunction OverloadingC++ supports writing more than one function C++ supports writing more than one function
with the same name but different argument with the same name but different argument lists. This could includelists. This could include::
–different data typesdifferent data types–different number of argumentsdifferent number of arguments
The advantage is that the same apparent The advantage is that the same apparent function can be called to perform similar but function can be called to perform similar but different tasks. The following will show an different tasks. The following will show an example of thisexample of this..
Function OverloadingFunction Overloadingvoidvoid swap swap (int(int *a, *a, intint *b *b)) ;;
voidvoid swap swap (float(float *c, *c, floatfloat *d *d)) ;;
voidvoid swap swap (char(char *p, *p, charchar *q *q)) ;;
int mainint main ( ) ( )
}}
intint a = 4, b = 6 a = 4, b = 6 ;;
floatfloat c = 16.7, d = -7.89 c = 16.7, d = -7.89 ;;
charchar p = 'M' , q = 'n p = 'M' , q = 'n ' ';;
swap swap ((&a, &b&a, &b)); ;
swap swap ((&c, &d&c, &d)) ;;
swap swap ((&p, &q&p, &q)) ;;
{ {
Function OverloadingFunction Overloadingvoidvoid swap swap (int(int *a, *a, intint *b *b))
} }intint temp temp;; temp = *a temp = *a;; *a = *b *a = *b;; *b = temp *b = temp{ ;{ ;
voidvoid swap swap (float(float *c, *c, floatfloat *d *d))
}} floatfloat temp temp;; temp = *c temp = *c;; *c = *d *c = *d;; *d = temp *d = temp;; {{
voidvoid swap swap (char(char *p, *p, charchar *q *q))
}} charchar temp temp;; temp = *p temp = *p; ; *p = *q *p = *q;; *q = temp *q = temp;; {{
Friend functions, operator Friend functions, operator overloadingoverloading
– –Friend functions, operator overloadingFriend functions, operator overloading
It’s good to have friendsIt’s good to have friends
A A friendfriend function of a class is defined outside the function of a class is defined outside the class’s scope (I.e. class’s scope (I.e. notnot member functions), yet has member functions), yet has the right to access the non-public members of the the right to access the non-public members of the
classclass..Single functions or entire classes may be declared Single functions or entire classes may be declared
as friends of a classas friends of a class..These are commonly used in operator These are commonly used in operator
overloading. Perhaps the most common use of overloading. Perhaps the most common use of friend functions is friend functions is overloading << and >>overloading << and >> for I/O for I/O..
FriendsFriends
Basically, when you declare something as a friend, Basically, when you declare something as a friend, you give it access to your private data membersyou give it access to your private data members..
This is useful for a lot of things – for very This is useful for a lot of things – for very interrelated classes, it more efficient (faster) than interrelated classes, it more efficient (faster) than using tons of get/set member function calls, and using tons of get/set member function calls, and they increase they increase encapsulation encapsulation by allowing more by allowing more
freedom is design optionsfreedom is design options..
FriendsFriends
A class doesn't control the scope of friend A class doesn't control the scope of friend functions so friend function declarations are functions so friend function declarations are
usually written at the beginning of a .h file. Public usually written at the beginning of a .h file. Public and private don't apply to themand private don't apply to them . .
Friends (a few gory details)Friends (a few gory details)
Friendship is not inherited, transitive, or reciprocalFriendship is not inherited, transitive, or reciprocal..–Derived classes don’t receive the privileges of friendship (more on Derived classes don’t receive the privileges of friendship (more on
this when we get to inheritance in a few classes)this when we get to inheritance in a few classes)–The privileges of friendship aren’t transitive. If class A declares The privileges of friendship aren’t transitive. If class A declares
class B as a friend, and class B declares class C as a friend, class class B as a friend, and class B declares class C as a friend, class C doesn’t necessarily have any special access rights to class AC doesn’t necessarily have any special access rights to class A..
–If class A declares class B as a friend (so class B can see class A’s If class A declares class B as a friend (so class B can see class A’s private members), class A is not automatically a friend of class B private members), class A is not automatically a friend of class B (so class A cannot necessarily see the private data members of (so class A cannot necessarily see the private data members of
class B)class B)..
FriendsFriends
class someClassclass someClass} } friend void setX( someClass&, int)friend void setX( someClass&, int);;int someNumberint someNumber;;
… …rest of class definitionrest of class definition{ {
// //a function called setX defined in a programa function called setX defined in a programvoid setX( someClass &c, int val)void setX( someClass &c, int val)} } c.someNumber = valc.someNumber = val{ ;{ ;
// //inside a main functioninside a main functionsomeClass myClasssomeClass myClass;;
setX (myClass, 5); setX (myClass, 5); //this will work, since we declared //this will work, since we declared // setX as a friend// setX as a friend
Nested Class DeclarationsA class can be declared within the scope of another class. Such a class is called a "nested class." Nested classes are considered to be within the scope of the enclosing class and are available for use within that scope. To refer to a nested class from a scope other than its immediate enclosing scope, you must use a fully qualified name.
value class Outside { value class Inside { }; }; In the same way, you can value class Outside { value class Inside { }; }; In the same way, you can nest as many classes as you wish in another class and you can nest nest as many classes as you wish in another class and you can nest
as many classes inside of other nested classes if you judge it as many classes inside of other nested classes if you judge it necessary. Just as you would manage any other class so can you necessary. Just as you would manage any other class so can you
exercise control on a nested class. For example, you can declare all exercise control on a nested class. For example, you can declare all necessary variables or methods in the nested class or in the nesting necessary variables or methods in the nested class or in the nesting
class. When you create one class inside of another, there is no special class. When you create one class inside of another, there is no special programmatic relationship between both classes: just because a class programmatic relationship between both classes: just because a class is nested doesn't mean that the nested class has immediate access to is nested doesn't mean that the nested class has immediate access to the members of the nesting class. They are two different classes and the members of the nesting class. They are two different classes and
they can be used separatelythey can be used separately . .The name of a nested class is not "visible" outside of the nesting class. The name of a nested class is not "visible" outside of the nesting class.
To access a nested class outside of the nesting class, you must qualify To access a nested class outside of the nesting class, you must qualify the name of the nested class anywhere you want to use it. This is done the name of the nested class anywhere you want to use it. This is done
using the :: operator. For example, if you want to declare an Inside using the :: operator. For example, if you want to declare an Inside variable somewhere in the program but outside of Outside, you must variable somewhere in the program but outside of Outside, you must
qualify its name. Here is an examplequalify its name. Here is an example::
using namespace Systemusing namespace System ; ;value class COutsidevalue class COutside
} } public: void ShowOutsidepublic: void ShowOutside()()
} } Console::WriteLine(L"=-= Outside =-=")Console::WriteLine(L"=-= Outside =-=") ; ;
{ { value class CInsidevalue class CInside
} } public: void ShowInsidepublic: void ShowInside () ()
} } Console::WriteLine(L"-=- Inside -=-")Console::WriteLine(L"-=- Inside -=-") ; ; ;{ ;{ { ;{ ;{ {