Object oriented programming involves modeling real-world entities as objects that encapsulate both data and behavior. Programmers define classes that specify the attributes and methods of these objects. This is a different approach than traditional procedural programming, as it focuses on objects rather than functions.
1. 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).
2. 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
3. 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.
4. 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();
}
5. 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
6. 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
7. 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
8. 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
9. 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
10. 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
11. 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
12. 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
13. 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
14. 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
15. 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.
16. Classes in C++Classes in C++
class class_name
}
private:
…
…
…
public:
…
…
…
;{
Public members or methods
private members or
methods
17. 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)
18. 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;
19. 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
20. 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
21. 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( ){( ){
……
}}
22. 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
24. 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
25. 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
26. 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??
27. 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..
28. 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..
29. 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..
33. 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
34. 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
35. 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
36. 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
37. 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
38. Abstract Data TypesAbstract Data Types
Figure 3.1
Isolated tasks: the implementation of task T does not affect task Q
39. 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
40. 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
41. 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
42. 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
43. Abstract Data TypesAbstract Data Types
Figure 3.4
A wall of ADT operations isolates a data structure from the program that uses it
44. 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
45. 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
46. 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
47. 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
48. The ADT ListThe ADT List
Figure 3.7
The wall between displayList and the implementation of the ADT list
49. 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??
50. 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
51. 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
52. 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
55. 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
56. 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((;((;
;};}
57. 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
58. 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
59. 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
60. 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
61. 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
62. 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
63. 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
64. 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
65. 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}}
… …… …
;};}
66. 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
67. 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
68. 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
69. 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
71. 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
72. 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
;};}
75. 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
76. 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;{;{
;};}
77. 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
78. 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
79. 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
82. 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
83. 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..
84. 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..
86. 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
87. 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)(;)(;
{{
88. 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
89. 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..
90. 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((;;
93. 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..
94. 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..
95. 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..
96. 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(.(.
97. 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
98. 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
99. 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::
Instructor notes:
When specifying the inheritance of a derived class from a base class, we have three options public, protected, and private. Here we look at public inheritance. This is the most common form of inheritance. When we refer to public inheritance here we are referring to the base class access specifier (the word immediately to the left of the base class name). This is different from the access specifier for the data members.
So, when we do a public inheritance of derived class A from base class B, the members that were public in B are inherited as public in A. The members that were protected in B are inherited as protected in B. And, those that were private in B, are inherited as private in A but they are not accessible because they are already private in B. So, inherited members that are private in the base class will not be accessible via member functions in the derived class. That means, the only way for the derived class to access an inherited member that was private in the base class is for there to be a public member function in the base class B that accesses any private members in B. It is for this reason that we have the protected specifier.
Instructor notes:
Here we look at protected inheritance. In this case, members that were public in the base class are “promoted” to the more restricted access specifier state of protected in the derived class. The protected inherited members retain their original access level in the derived class.
Instructor notes:
Finally we look at private inheritance. In this case, members that were public or protected in the base class are “promoted” to the more restricted access specifier state of private in the derived class. This means that these members will be accessible by member functions of the derived class, but they will not be accessible in another derived class, that is one or more below A in the hierarchy. Again, base class members that were already private are private in the derived class, but they are not accessible by member functions of the derived class A because they are already private to the base class B.
Instructor notes:
Here we see a quick example of making use of inheritance based on our Shape class and its derived classes. Note that Shape has a public member function and a protected data member. If the data member color were private, rather than protected, then it would not be accessible from the derived classes Two_D, Three_D, Square, Cube and any other derived classes that might be created.
Both Two_D and Three_D inherit all of the data members and member functions that Shape contains while also, presumably, having functions and data that are specific to each of them.
Instructor notes:
On this slide we have the derived classes Square and Cube which are derived from Two_D and Three_D respectively. Again the data members in these derived classes are protected so that classes further derived from Square and/or Cube would be able to access the edge_length member through the further derived classes’ member functions.
A point to reemphasize...Square, for example, has all of the characteristics of Two_D as well as all of the characteristics of Shape without having to specify them explicitly in the class definition.
Instructor notes:
Now, inside the main () program we declare two objects, mySquare which is of class Square and myCube which is of class Cube. Because of inheritance, we can call the getColor () function from mySquare as well as from myCube, even though getColor () was defined in the Shape class. In addition we can call the getArea () and getVolume () functions from the derived Square and Cube objects, respectively.
Instructor notes:
Overloading is the ability to have multiple functions with the same name, but with different signatures. A function’s signature is a combination of its name and its argument list. So, if two functions have the same name, but have a different number of arguments, or different types of arguments, or even the same types, but in a different order such as float, float, int is different than float, int, float, then those two functions have different signatures and can be overloaded. The motivation behind overloading is to be able to use similar function calls to functions that essentially do the same thing, but process different data types. For example if we had a function that compared two integers to see which was larger and wanted to be able to do the same comparison on two floats, then we could overload the function. We would write two functions with the same name, but different signatures.
One important note, the return type is not part of the function signature. So, if you’re overloading a function, the return type cannot be the only difference between two versions of the overloaded function.
Instructor notes:
Here we see a quick example of function overloading using the swap () routine. We’ve got three different prototypes for swap (). The first expects integer pointers, the second expects float pointers, and the third expects char pointers. In our main () routine we initialize pairs of ints, floats, and chars. Then we call swap () with the only difference between the calls being the argument types. Therefore the signature of the swap () being called each time is different, and the compiler knows which version of swap to call.
On the next slide we see the different overloaded versions of swap ().
Instructor notes:
Here are our three different versions of the swap routine. Each expects pointers to variables, but the first expects pointers to ints, the second expects pointers to floats, and the last expects pointers to chars. When the calls to the swap function are made, as in main (), the compiler matches up the signature of the function being called with the function definition that corresponds to it and calls the correct version.
So, in the main () routine here the calls to the functions look very similar, with the only difference being the types of arguments.