Object Oriented ProgrammingObject Oriented Programming
 ProgrammerProgrammer thinksthinks about and defines theabout 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 thanVery 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 functionsEncapsulates 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 isThe 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 useuse
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 otherClass 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 andPublic part consists of variables and
functions that are visiblefunctions that are visible outsideoutside of theof the
modulemodule..
Private part consists of variables andPrivate part consists of variables and
functions visible onlyfunctions visible only withinwithin the modulethe module..
Modules may span multiple compilationModules may span multiple compilation
units (filesunits (files(.(.
Modules generally lack any inheritanceModules generally lack any inheritance
mechanismmechanism..
Modules
Why OO-ProgrammingWhy OO-Programming??
ReducesReduces conceptual loadconceptual load by reducingby reducing
amount of detailamount of detail
ProvidesProvides fault containmentfault containment
–Can’t use components (e.g., a class) inCan’t use components (e.g., a class) in
inappropriate waysinappropriate ways
ProvidesProvides independenceindependence betweenbetween
componentscomponents
–Design/development can be done by more thanDesign/development can be done by more than
one personone person
Global Variables -lifetime spans programGlobal Variables -lifetime spans program
executionexecution..
Local Variables - lifetime limited to executionLocal 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 shareModules - allow several subroutines to share
a set of static variablesa set of static variables..
Module Types - multiple instances of anModule 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 anAn instance of a class is know as an
ObjectObject..
Languages that are based on classes areLanguages that are based on classes are
know asknow as Object-OrientedObject-Oriented..
–EiffelEiffel
–CC++++
–Modula-3Modula-3
–Ada 95Ada 95
–JavaJava
Keys to OO Programming
Encapsulation (data hidingEncapsulation (data hiding((
–Enable programmer to group data & subroutinesEnable 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 beEnable 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) toEnable 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 keywordA class definition begins with the keyword
classclass..
 The body of the class is contained within aThe 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 keywordsWithin the body, the keywords private:private: andand
public:public: specify the access level of thespecify the access level of the
members of the class.members of the class.
– the default isthe default is privateprivate..
 Usually, the data members of a class areUsually, the data members of a class are
declared in thedeclared in the private:private: section of the classsection of the class
and the member functions are inand 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 canThis class example shows how we can
encapsulate (gather) a circle informationencapsulate (gather) a circle information
into one package (unit or class)into 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. The
class methods are responsible for
that only.
They are accessible from outside
the class, and they can access the
member (radius)
Creating an object of a ClassCreating an object of a Class
 Declaring a variable of a class type creates anDeclaring 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, aOnce an object of a certain class is instantiated, a
new memory location is created for it to store itsnew memory location is created for it to store its
data members and codedata members and code
 You can instantiate many objects from a classYou 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 createdcalled 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 classClass 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 sameDifferent 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, classDo 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 forIdentical 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 toExtends the scope rules of modules to
include inheritanceinclude inheritance..
Should private members of a base class beShould private members of a base class be
visible in derived classesvisible in derived classes??
Should public members of a base classShould public members of a base class
always be public members of a derivedalways be public members of a derived
classclass..
How much control should a base classHow 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 itsAny class can limit the visibility of its
membersmembers::
–PublicPublic members are visible anywhere the classmembers are visible anywhere the class
is in scopeis in scope..
–PrivatePrivate members are visible only within themembers are visible only within the
class’s methodsclass’s methods..
–ProtectedProtected members are visible inside membersmembers are visible inside members
of the class and derived classesof the class and derived classes..
–FriendFriend classes are granted exceptions toclasses are granted exceptions to
(some) of the rules(some) of the rules..
C++ ClassesC++ Classes
Derived classes can further restrict visibility ofDerived 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 aPrivate members of a base class are never visible in a
derived classderived class..
–Protected and public members of a public base classProtected 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 baseProtected 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 classProtected 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 classDerived classes that limit visibility of base class
members can restore visibility by inserting amembers can restore visibility by inserting a
using declaration in its protected or publicusing declaration in its protected or public
sectionssections..
Rules in other languages can be significantlyRules in other languages can be significantly
differentdifferent..
Dynamic Method BindingDynamic Method Binding
Member LookupMember Lookup
InheritanceInheritance
EncapsulationEncapsulation
Encapsulation Requires that functions,Encapsulation Requires that functions,
modules and classesmodules and classes::
–Have clearly defined external interfacesHave clearly defined external interfaces
–Hide implementation detailsHide implementation details
private data
private
functions
public functions
Abstract Data TypesAbstract Data Types
ModularityModularity
–Keeps the complexity of a large programKeeps the complexity of a large program
manageable by systematically controllingmanageable by systematically controlling
the interaction of its componentsthe interaction of its components
–Isolates errorsIsolates errors
Abstract Data TypesAbstract Data Types
Modularity (ContinuedModularity (Continued))
–Eliminates redundanciesEliminates redundancies
–A modular program isA modular program is
Easier to writeEasier to write
Easier to readEasier to read
Easier to modifyEasier to modify
Abstract Data TypesAbstract Data Types
Procedural abstractionProcedural abstraction
–Separates the purpose and use of a moduleSeparates 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 behaves
Identify 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 aHides certain implementation details within a
modulemodule
–Makes these details inaccessible from outsideMakes 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 withFunctions’ specifications, or contracts, govern how they interact with
each othereach 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 dataAsk questions about the data in a data
collectioncollection
Abstract Data TypesAbstract Data Types
Data abstractionData abstraction
–Asks you to thinkAsks you to think whatwhat you can do to ayou can do to a
collection of data independently ofcollection of data independently of howhow you do ityou do it
–Allows you to develop each data structure inAllows 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 (ADTAbstract data type (ADT))
–An ADT is composed ofAn ADT is composed of
A collection of dataA collection of data
A set of operations on that dataA set of operations on that data
–Specifications of an ADT indicateSpecifications of an ADT indicate
What the ADT operations do, not how to implementWhat the ADT operations do, not how to implement
themthem
–Implementation of an ADTImplementation of an ADT
Includes 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 itemExcept for the first and last items, each item
has a unique predecessor and a uniquehas a unique predecessor and a unique
successorsuccessor
Head or front do not have a predecessorHead or front do not have a predecessor
Tail 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 withinItems 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 toDo not specify how to store the list or how to
perform the operationsperform the operations
ADT operations can be used in anADT operations can be used in an
application without the knowledge of howapplication 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, notInserts 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 evolveThe 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, theFor complex abstract data types, the
behavior of the operations must be specifiedbehavior 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 theChoosing 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 on
Details of the ADT’s operationsDetails of the ADT’s operations
Context in which the operations will be usedContext in which the operations will be used
Implementing ADTsImplementing ADTs
Implementation details should be hiddenImplementation details should be hidden
behind a wall of ADT operationsbehind a wall of ADT operations
–A program would only be able to access theA program would only be able to access the
data structure using the ADT operationsdata structure using the ADT operations
Implementing ADTsImplementing ADTs
Figure 3.8
ADT operations provide access to a data structure
Implementing ADTsImplementing ADTs
Figure 3.9 Violating the wall of ADT operations
C++ ClassesC++ Classes
Encapsulation combines an ADT’s data withEncapsulation 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 memberA class contains data members and member
functionsfunctions
By default, all members in a class areBy 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 nVvoid 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 nVvoid 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 nVvoid set(float *x, float *y, int nV(;(;
float areafloat area((;((;
;};}
Rectangle Triangle
Polygon
class Polygonclass Polygon}}
protectedprotected::
int numVerticesint numVertices;;
float *xCoord, float *yCoordfloat *xCoord, float *yCoord;;
publicpublic::
void set(float *x, float *y, int nVvoid set(float *x, float *y, int nV(;(;
;};}
class Rectangle : public Polygonclass Rectangle : public Polygon}}
publicpublic::
floatfloat areaarea((;((;
;};}
class Rectangleclass Rectangle}}
protectedprotected::
int numVerticesint numVertices;;
float *xCoord, float *yCoordfloat *xCoord, float *yCoord;;
publicpublic::
void set(float *x, float *y, int nVvoid set(float *x, float *y, int nV(;(;
float areafloat area((;((;
;};}
Inheritance ConceptInheritance Concept
Rectangle Triangle
Polygon
class Polygonclass Polygon}}
protectedprotected::
int numVerticesint numVertices;;
float *xCoord, float *yCoordfloat *xCoord, float *yCoord;;
publicpublic::
void set(float *x, float *y, int nVvoid set(float *x, float *y, int nV(;(;
;};}
class Triangle : publicclass 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 nVvoid 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 bvoid set (int a, int b(;(;
;};}
class Circle : public Pointclass Circle : public Point}}
privateprivate::
double rdouble r;;
;};}
class 3D-Point: publicclass 3D-Point: public
PointPoint}}
privateprivate::
int zint z;;
;};}
x
y
x
y
r
x
y
z
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
real
imag
real imag
3D-Point
Why InheritanceWhy Inheritance??
Inheritance is a mechanism forInheritance is a mechanism for
building class types from existing classbuilding 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-levelaccess-level specifies the type of derivationspecifies the type of derivation
private by default, orprivate by default, or
publicpublic
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 bvoid 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, every member of a base class
is inherited by a derived classis inherited 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 controlTwo levels of access control
over class membersover class members
–class definitionclass definition
–inheritance typeinheritance type
b a s e c la s s / s u p e rc la s s /
p a re n t c la s s
d e riv e d c la s s / s u b c la s s /
c h ild c la s s
derivefrom
membersgoesto
class Pointclass Point}}
protected:protected: int x, yint x, y;;
public:public: void set(int a, int bvoid set(int a, int b(;(;
;};}
class Circle :class Circle : publicpublic PointPoint}}
… …… …
;};}
The type of inheritance defines the access level for theThe type of inheritance defines the access level for the
members of derived classmembers of derived class that are inherited from thethat are inherited from the
base classbase class
Access Rights or accessAccess Rights or access
specifiers of Derived Classesspecifiers of Derived Classes
privateprivate protectedprotected publicpublic
privateprivate -- -- --
protecteprotecte
dd
privateprivate protectedprotected protectedprotected
publicpublic privateprivate protectedprotected publicpublic
Type of Inheritance
AccessControl
forMembers
Public InheritancePublic Inheritance
public base classpublic base class
(B(B((
public memberspublic members
protectedprotected
membersmembers
derived class (Aderived class (A((
publicpublic
protectedprotected
inherited but notinherited but not
accessibleaccessible
classclass AA : public: public BB
}}////Class A now inherits the members of Class BClass A now inherits the members of Class B
////with no change in the “access specifier” forwith no change in the “access specifier” for
{{////the inherited membersthe inherited members
Protected InheritanceProtected Inheritance
protected baseprotected base
class (Bclass (B((
public memberspublic members
protectedprotected
membersmembers
derived class (Aderived class (A((
protectedprotected
protectedprotected
inherited but notinherited but not
accessibleaccessible
classclass AA : protected: protected BB
}}////Class A now inherits the members of Class BClass A now inherits the members of Class B
////withwith publicpublic members “promoted” tomembers “promoted” to protectedprotected
{{////but no other changes to the inherited membersbut no other changes to the inherited members
Private InheritancePrivate Inheritance
private base classprivate base class
(B(B((
public memberspublic members
protectedprotected
membersmembers
derived class (Aderived class (A((
privateprivate
privateprivate
inherited but notinherited but not
accessibleaccessible
classclass AA : private: private BB
}}////Class A now inherits the members of ClassClass A now inherits the members of Class
BB
////withwith publicpublic andand protectedprotected membersmembers
{{// “// “promoted” topromoted” to privateprivate
class daughter :class daughter : ------------------ mothermother}}
private: double dPrivprivate: double dPriv;;
public: void mFoopublic: void mFoo( (;( (;
;};}
Class DerivationClass Derivation
class 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/public
int mainint main(( }(( }
/*.…*//*.…*/
}}
class grandDaughter :class grandDaughter : publicpublic daughterdaughter}}
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-Since all these functions are class-
specificspecific
Inheritance (continuedInheritance (continued((
classclass ShapeShape
{{
publicpublic::
intint GetColorGetColor( ( ;( ( ;
////so derived classes can access itso derived classes can access it
protectedprotected::
intint colorcolor;;
;};}
classclass Two_DTwo_D :: publicpublic ShapeShape
{{
////put members specific to 2D shapes hereput members specific to 2D shapes here
;};}
classclass Three_DThree_D :: publicpublic ShapeShape
{{
////put members specific to 3D shapes hereput members specific to 3D shapes here
;};}
Inheritance (continuedInheritance (continued((
classclass SquareSquare :: publicpublic Two_DTwo_D
{{
publicpublic::
floatfloat getAreagetArea( ( ;( ( ;
protectedprotected::
floatfloat edge_lengthedge_length;;
; }; }
classclass CubeCube :: publicpublic Three_DThree_D
{{
publicpublic::
floatfloat getVolumegetVolume( ( ;( ( ;
protectedprotected::
floatfloat edge_lengthedge_length;;
Inheritance (continuedInheritance (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 bvoid set(int a, int b(;(;
;};}
class Circle : public Pointclass Circle : public Point}}
privateprivate::
double rdouble r;;
publicpublic::
void set_r(double cvoid set_r(double c(;(;
;};}
x
y
x
y
r
class Circleclass Circle}}
protectedprotected::
int x, yint x, y;;
privateprivate::
double rdouble r;;
publicpublic::
void set(int a, int bvoid set(int a, int b(;(;
void set_r(double cvoid 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 canA derived class can overrideoverride methods defined in itsmethods defined in its
parent class. With overridingparent class. With overriding,,
–the method in the subclass has the identical signature to thethe 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 classa subclass implements its own version of a base class
methodmethod..
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::
voidvoid setset(int a, int b(int a, int b((
}}x=a; y=bx=a; y=b;{;{
voidvoid foofoo((;((;
voidvoid printprint((;((;
;};}
class Circle : public Pointclass Circle : public Point}}
private: double rprivate: double r;;
publicpublic::
voidvoid 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;;
}}
voidvoid 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.foofoo ((; // 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 Point// from base class Point
A.A.printprint((;((; // from base class Point// from base class Point
Putting Them TogetherPutting Them Together
TimeTime is the base classis the base class
ExtTimeExtTime is the derived classis the derived class
with public inheritancewith public inheritance
The derived class canThe derived class can
–inherit all members from theinherit all members from the
base class, except thebase class, except the
constructorconstructor
–access all public and protectedaccess 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 memberdefine its public member
functionsfunctions
–override functions inherited fromoverride functions inherited from
the base classthe base class
ExtTime
Time
Take Home MessageTake Home Message
Inheritance is a mechanism for definingInheritance is a mechanism for defining
new class types to be a specialization ornew class types to be a specialization or
an augmentation of existing typesan augmentation of existing types..
In principle, every member of a base classIn principle, every member of a base class
is inherited by a derived class withis inherited by a derived class with
different access permissions, except fordifferent access permissions, except for
the constructorsthe constructors
POLYMORPHISMPOLYMORPHISM
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 types
polymorphism
Run-time
polymorphismCompile-time
polymorphism
Operator overloadingFunction Overloading Virtual functions
Compile time polymorphismCompile time polymorphism
Binding of Function call and functionBinding of Function call and function
definition is done during compile time. Thisdefinition is done during compile time. This
is known asis known as static bindingstatic binding..
InIn function overloading and operatorfunction overloading and operator
overloadingoverloading static binding happens, hencestatic binding happens, hence
they come under compile timethey come under compile time
polymorphismpolymorphism..
Run-time polymorphismRun-time polymorphism
Binding of Function call and functionBinding of Function call and function
definition is done during Run time. This isdefinition is done during Run time. This is
known as late orknown as late or dynamic bindingdynamic binding..
If late binding happens in polymorphism it isIf late binding happens in polymorphism it is
known as run-time polymorphismknown as run-time polymorphism
C++ supports a mechanism known asC++ supports a mechanism known as
virtual functionsvirtual functions to achieve run-timeto achieve run-time
polymorphismpolymorphism..
ExampleExample::
Class personClass person
}}
char name[30char name[30[;[;
float agefloat age;;
publicpublic::
person(char *s,float aperson(char *s,float a((
}}
strcpy(name,sstrcpy(name,s(;(;
age=aage=a;;
{{
person& greater(person &xperson& greater(person &x((
}}
if(x.age>=ageif(x.age>=age((
return xreturn x;;
elseelse
return *thisreturn *this;;
{{
void display (voidvoid display (void((
}}
cout<<name<<agecout<<name<<age;;
{{
;{;{
Abstract ClassesAbstract Classes
An abstract class represents an abstract concept in C++ (suchAn abstract class represents an abstract concept in C++ (such
as Shape classas 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”,32Person P1)“john”,32(;(;
Person P2)“ahmed”,38Person P2)“ahmed”,38(;(;
Person P3)“karthik”,30Person P3)“karthik”,30(;(;
Person p=P1.greater)P2Person p=P1.greater)P2(;(;
cout <<“elder personcout <<“elder person”;”;
p.displayp.display)(;)(;
p=P3.greater)P2p=P3.greater)P2(;(;
cout<<“younger personcout<<“younger person”;”;
p.displayp.display)(;)(;
{{
Abstract ClassesAbstract Classes
An abstract class represents an abstract concept in C++ (suchAn abstract class represents an abstract concept in C++ (such
as Shape classas 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 Overloading
C++ supports writing more than one functionC++ supports writing more than one function
with the same name but different argumentwith 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 apparentThe advantage is that the same apparent
function can be called to perform similar butfunction can be called to perform similar but
different tasks. The following will show andifferent tasks. The following will show an
example of thisexample of this..
Function OverloadingFunction Overloading
voidvoid swapswap )int)int *a,*a, intint *b*b((;;
voidvoid swapswap )float)float *c,*c, floatfloat *d*d((;;
voidvoid swapswap )char)char *p,*p, charchar *q*q((;;
int mainint main) () (
}}
intint a = 4, b = 6a = 4, b = 6;;
floatfloat c = 16.7, d = -7.89c = 16.7, d = -7.89;;
charchar p = 'M' , q = 'np = 'M' , q = 'n'';;
swapswap ))&a, &b&a, &b( ;( ;
swapswap ))&c, &d&c, &d((;;
Function OverloadingFunction Overloading
voidvoid swapswap )int)int *a,*a, intint *b*b((
{{intint temptemp;; temp = *atemp = *a;; *a = *b*a = *b;; *b = temp*b = temp; }; }
voidvoid swapswap )float)float *c,*c, floatfloat *d*d((
{{floatfloat temptemp;; temp = *ctemp = *c;; *c = *d*c = *d;; *d = temp*d = temp;;}}
voidvoid swapswap )char)char *p,*p, charchar *q*q((
{{charchar temptemp;; temp = *ptemp = *p;; *p = *q*p = *q;; *q = temp*q = temp;;}}
Friend functions, operatorFriend functions, operator
overloadingoverloading
––Friend functions, operator overloadingFriend functions, operator overloading
It’s good to have friendsIt’s good to have friends
AA friendfriend function of a class is defined outside thefunction of a class is defined outside the
class’s scope )I.e.class’s scope )I.e. notnot member functions(, yet hasmember functions(, yet has
the right to access the non-public members of thethe right to access the non-public members of the
classclass..
Single functions or entire classes may be declaredSingle functions or entire classes may be declared
as friends of a classas friends of a class..
These are commonly used in operatorThese are commonly used in operator
overloading. Perhaps the most common use ofoverloading. Perhaps the most common use of
friend functions isfriend functions is overloading << and >>overloading << and >> for I/Ofor 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 veryThis is useful for a lot of things – for very
interrelated classes, it more efficient )faster( thaninterrelated classes, it more efficient )faster( than
using tons of get/set member function calls, andusing tons of get/set member function calls, and
they increasethey increase encapsulationencapsulation by allowing moreby allowing more
freedom is design optionsfreedom is design options..
FriendsFriends
A class doesn't control the scope of friendA class doesn't control the scope of friend
functions so friend function declarations arefunctions so friend function declarations are
usually written at the beginning of a .h file. Publicusually 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 detailsFriends )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 onDerived classes don’t receive the privileges of friendship )more on
this when we get to inheritance in a few classesthis when we get to inheritance in a few classes((
–The privileges of friendship aren’t transitive. If class A declaresThe privileges of friendship aren’t transitive. If class A declares
class B as a friend, and class B declares class C as a friend, classclass 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’sIf 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 Bprivate 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 Bclass B(.(.
FriendsFriends
class someClassclass someClass{{
friend void setX) someClass&, intfriend 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 program
void setX) someClass &c, int valvoid setX) someClass &c, int val( {( {
c.someNumber = valc.someNumber = val; }; }
////inside a main functioninside a main function
someClass 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
ass Declarations
n be declared within the scope of another clas
ass." Nested classes are considered to be with
class and are available for use within that scop
a scope other than its immediate enclosing sc
name
value class Outside { value class Inside { }; }; In the same way, you canvalue class Outside { value class Inside { }; }; In the same way, you can
nest as many classes as you wish in another class and you can nestnest as many classes as you wish in another class and you can nest
as many classes inside of other nested classes if you judge itas many classes inside of other nested classes if you judge it
necessary. Just as you would manage any other class so can younecessary. Just as you would manage any other class so can you
exercise control on a nested class. For example, you can declare allexercise control on a nested class. For example, you can declare all
necessary variables or methods in the nested class or in the nestingnecessary variables or methods in the nested class or in the nesting
class. When you create one class inside of another, there is no specialclass. When you create one class inside of another, there is no special
programmatic relationship between both classes: just because a classprogrammatic relationship between both classes: just because a class
is nested doesn't mean that the nested class has immediate access tois nested doesn't mean that the nested class has immediate access to
the members of the nesting class. They are two different classes andthe 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 qualifyTo 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 donethe 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 Insideusing the :: operator. For example, if you want to declare an Inside
variable somewhere in the program but outside of Outside, you mustvariable 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"=-= OutsideConsole::WriteLine)L"=-= Outside=-="(;=-="(;
{{
value class CInsidevalue class CInside
}}
public: void ShowInsidepublic: void ShowInside)()(
{{Console::WriteLine)L"-=- InsideConsole::WriteLine)L"-=- Inside-=-"(;-=-"(;
;{ ;{ {;{ ;{ {