Object Oriented Programming: Inheritance

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 52

Object Oriented Programming

Inheritance

12/08/21 QAU-IT-2010-Fall 1
Treating Similar Classes
 Our programs model a variety of real-life objects
through their data and operations
 The modeling of real-life entities should ideally reflect
"common features" among real objects
 We use the class construct to capture commonality of
objects when
 We believe that these objects can be characterized by
 the same sets of attributes
 the same patterns of behavior

12/08/21 QAU-IT-2010-Fall 2
Treating Similar Classes
 Often, commonalities might exist among classes
 The groups of objects might have basically similar but
still somewhat different sets of attributes and operations
 Employees
 Hourly employees
 Salaried employees
 Some object groups might have somewhat different sets
of operations or provide additional operations
 Current account
 Saving account

12/08/21 QAU-IT-2010-Fall 3
Merging Subclass Features in a Class
 Merging all these characteristics into one class will
satisfy the client code requirements
 But it is inherently unsafe
 The client code might use the object incorrectly,
assuming the presence of the features
 Merging all attributes and operations into one class to
provide for all possible alternatives is a viable method of
abstraction
 But client have to take care of the correct use of objects

12/08/21 QAU-IT-2010-Fall 4
Merging Subclass Features in a Class
 You cannot prevent all coding mistakes
 You should prevent mistakes as many as possible
 This design needs to be improved
 Client code makes an explicit comment about the
nature of each object of a class of merged

12/08/21 QAU-IT-2010-Fall 5
Pushing Responsibility to the Server

 To avoid the danger of incorrect use of a server object


 Add to the server class an additional attribute, a tag
field, Kind!
 It means that you are introducing subclasses to class
 The constructors for two different kinds of accounts
have a different number of parameters
 Enumerations can be used for Kind to enhance
readability
 The constructor code would include a parameter for the
kind of object
12/08/21 QAU-IT-2010-Fall 6
Pushing Responsibility to the Server
 What the code designer has now expressed in code so that
the designer's knowledge is transmitted to the maintainer
 You should always weigh conciseness against increase in
coordination and decrease in understandability
 Merging data and operations of different subtypes in one
class, each server method enforces its legal operations
 The server class needs additional code for type analysis
 For a large system with a large number of object kinds??
 Client coding errors are still run-time, not compile-time

12/08/21 QAU-IT-2010-Fall 7
Separate Classes for Each Kind
 A good solution to this problem is to design a set of
separate classes
 Each of these classes is designed from scratch
 e.g each type of account
 This design resolves the problem of erroneous client
use beautifully
 Instead of a run-time error, a compile-time error is
generated
 It does not convey the designer's knowledge to the
maintainer well

12/08/21 QAU-IT-2010-Fall 8
Using C++ Inheritance to Link
Related Classes
 The designer of these classes knows that they have
these features in common, but this knowledge is not
conveyed to the maintenance programmer
 Inheritance is another solution to this problem
 You create a class, which contains the common
denominator of features common to all subtypes
 In terms of object-oriented analysis and design, this
class represents the generalization of state and behavior
of these subclasses

12/08/21 QAU-IT-2010-Fall 9
Using C++ Inheritance to Link
Related Classes
 Reuse the common features for other specialized classes
 Each specialized class adds specialized features to the
generalized class
 Protected keyword
 Base class Vs Derived classes (Java uses extension)
 Super class or parent class and Subclass or Child class
 Derived classes add and sometimes replace features of a
more-general base class
 Additional data and methods in derived classes reflect the
relationship of specialization among classes

12/08/21 QAU-IT-2010-Fall 10
Using C++ Inheritance to Link
Related Classes
 There exist "natural" super class/subclass relationships
among real world entities
 If relationship “A Kind of” exists between entities then
they can be related through inheritance
 Inheritance can be either direct or indirect
 Inheritance can be used as a tool for division of labor
in software development
 The base and derived classes can be developed by
different programmers

12/08/21 QAU-IT-2010-Fall 11
Using C++ Inheritance
 A good way to enhance abstraction, the use of
commonality in classes results in less code to write
and in better modularization
 However code amount depends on different aspects
as well
 Another popular use of inheritance is for run-time
binding of methods
 Static and dynamic binding of methods
 Polymorphism is a special case of object-oriented
programming

12/08/21 QAU-IT-2010-Fall 12
Using C++ Inheritance
 Polymorphism allows you to process a list of objects
 Syntax of C++ Inheritance
 Name of base class
 Different Modes of Derivation from the Base Class
inheritance—public, private, or protected
 What is private in the base remains private in the
derived class and so on
 Capabilities of base classes are not lost at the bottom
of the hierarchy of derived classes
 Inheritance enhances modularization and code reuse
12/08/21 QAU-IT-2010-Fall 13
Inheritance - Reuse
 A group of well-designed general purpose classes can be
organized into a library
 The library classes can be customized by creating new
derived classes
 Application programmers use the capabilities
implemented in library classes and only add specific
capabilities
 Normally, base classes need neither editing nor
recompilation
 The client code, does not have to know about derivation

12/08/21 QAU-IT-2010-Fall 14
Defining and Using Objects of Base
and Derived Classes
 When the client code needs an object, it can define and use
objects of the base class and the derived classes
 Method calls for base and derived classes…
 Objects of the base class behave in the client code as if
derived classes do not exist
 When the target of the message is an object of a derived
class Then
 The method is inherited from the base class as is and is not redefined
in the derived class.
 The method is absent in the base class and is added to the derived
 The method is present in the base class and is redefined by the derived

12/08/21 QAU-IT-2010-Fall 15
Object Oriented Principle and C++
 Notice that the use of inheritance breaks the first
principle of object-oriented programming:
 Binding data and operations together in the class definition
within the boundaries of the class scope
 C++ claims that an object of the derived class is an
object of the base class (plus more) and hence has all
data and methods defined in the base class
 C++ makes the scope of the derived class nested within
the scope of the base class
 Derived class pointer can be save in Base class pointer

12/08/21 QAU-IT-2010-Fall 16
Public Inheritance

12/08/21 QAU-IT-2010-Fall 17
Protected Inheritance

12/08/21 QAU-IT-2010-Fall 18
Private Inheritance

12/08/21 QAU-IT-2010-Fall 19
Members Access
 Adjusting Access to Base Members in the Derived Class
 Default inheritance mode : private
 The default mode of inheritance for a C++ structure is
public
 Keywords class and struct denote the same thing with
the exception of default access rights
 This is consistent with the default C++ rules for access
to class members

12/08/21 QAU-IT-2010-Fall 20
Scope Rules Under Inheritance
 Class scope can be viewed as nested under derivation
 General theory of nested scopes is applicable
 Derived class members are invisible in the scope of the
base class
 Use scope resolution operator to resolve name conflicts
 Name Overloading and Name Hiding
 The function signature is not a deciding factor
 It does not matter for the resolution of nested inheritance
scopes
 No function overloading Base to derived range

12/08/21 QAU-IT-2010-Fall 21
Scope Rules Under Inheritance
 Calling a Base Method Hidden by the Derived Class
 One remedy is to overload the method in the base class rather
than in the derived class
 Both functions are inherited by the derived class and can be
called through the derived class object
 The new method might need data that is defined in the derived
class and is not available in the base class
 The higher a class is in the inheritance hierarchy, the
more we want to guard this class against change
because the change can affect other derived classes
 Place the new method in the derived class with params

12/08/21 QAU-IT-2010-Fall 22
Program Evolution using Inheritance
 Most people try to change exiting code to accommodate
new changes
 Writing new code instead of modifying existing code
 Instead of looking for ways to change existing code, you
could look for the ways to inherit from existing classes
to support new requirements
 This a new way of thinking about writing code
 Weigh this approach against the drawbacks of
creating too many small classes

12/08/21 QAU-IT-2010-Fall 23
According to the principles of object-
oriented programming
 You do not want the client code to create dependencies
on server class data names
 You do not want to complicate the client code with
direct operations over data
 You do not want the client code to know more about
server design than is necessary
 You want the client code to call server methods whose
names explain the actions
 You want the client code to push responsibility for lower
level details to servers

12/08/21 QAU-IT-2010-Fall 24
Constructors and Destructors for
Derived Classes
 For class inheritance, the base part of the object is
always created before the derived part of the object is
created and before the derived class constructor is
executed
 Calling of Base class parameterized constructors
 Using Initialization Lists in Derived Class Constructors
 Destructors Under Inheritance
 The order of destructor invocation is opposite to that of
the order of constructor invocation.

12/08/21 QAU-IT-2010-Fall 25
Multiple Inheritance
 A derived class might have more than one base class.
This phenomenon is known multiple inheritance
 With single inheritance, the hierarchy of classes is a
tree, with the base class on the top of the hierarchy and
derived classes below the base class
 With multiple inheritance, the hierarchy of classes might
become a graph rather than a tree as with single
inheritance
 Multiple inheritance allows the server class designer to
mix the characteristics of diverse classes in one class

12/08/21 QAU-IT-2010-Fall 26
Multiple Inheritance
 Multiple inheritance is good for customizing existing
class libraries, for example, for adding or redefining
members in existing classes
 Each parent class contributes properties to the derived
class; the derived class is a union of the base features
 Examples of using multiple inheritance include graphic
objects, Now accounts, and iostream classes in the C++
standard library
 C++ does not put a limit on the number of base classes
that can participate in forming a derived class

12/08/21 QAU-IT-2010-Fall 27
Multiple Inheritance
 It is hard to come up with examples of multiple
inheritance with three or four base classes so that they
make good sense
 Use multiple inheritance with caution. The advantages
are few and complications are many
 There are always ways to adequately support the client
code without using multiple inheritance

12/08/21 QAU-IT-2010-Fall 28
Multiple Inheritance
 Access Rules
 A derived class inherits all members of all bases

 Access rules for multiple inheritance are the same as

for single : public, protected, or private


 Conversions Between Classes
 Conversion from a base class to the derived class is

not allowed
 A base object has only part of the data and

capabilities that a derived object has, and the missing


capabilities are nowhere to come from

12/08/21 QAU-IT-2010-Fall 29
Multiple Inheritance
 Constructors and Destructors
 All base class constructors are called before the derived

class constructor is called


 They are called in the order in which the base classes are

listed in the derived class declaration, not in the order of


the initialization list of the derived class constructor
 In the member initialization list, the Derived class

constructor calls base constructors using class names in a


comma-separated sequence of constructor calls
 Then the base class destructors are called in an order that

is the reverse of constructor invocations

12/08/21 QAU-IT-2010-Fall 30
Multiple Inheritance
 Ambiguities
 If two (or more) base classes have a data member with

the same name (of the same or different types), the


derived class object has both copies, and this results in
ambiguity
 Conflicts between names of data members should be

resolved by the derived class to avoid ambiguities and to


protect the client code. The scope operator has to be used
 Everything that can be done with the use of multiple
inheritance can be achieved as a combination of inheritance
and composition

12/08/21 QAU-IT-2010-Fall 31
Deciding between
Inheritance and Composition
 Composition Vs Inheritance
 Reusability, Maintainability, Understandability

 Impact of change

 Designer’s knowledge transfer to maintainer

 Server and client concept: Commons things among them

 Which to choose?
 Basic decision making: “a part of” and “a kind of”

 In case of ambiguity

 Pluses and Minuses of Inheritance & Composition

12/08/21 QAU-IT-2010-Fall 32
Virtual Functions
 The most common relationship is the relationship of containment
 The most general relationship is that of association
 Client class contains a pointer or a reference to an object of

the server class


 Degree of visibility of server object
 Being class member

 Being local variable in the function

 Being passed as function parameter

 Bering a pointer / reference of server class

 Inheritance

12/08/21 QAU-IT-2010-Fall 33
Advanced Inheritance
 The goal of utilizing inheritance is making the job of the
server class designer easier
 The goal of inheritance is making the job of the client
programmer easier by streamlining the client code
 When the client code deals with collections of similar objects
that undergo similar processing
 "Similar processing" means that the client code treats
different objects basically the same way
 Depending on the type of object, some things should be
done somewhat differently
 Client code have to use switch for differentiating objects

12/08/21 QAU-IT-2010-Fall 34
Virtual functions
 Programming with virtual functions and abstract classes
is often presented as the essence of object-oriented
programming
 Most of C++ code deals with cooperating objects and
does not need virtual functions
 Actually, most C++ code is (and should be) written
without the use of inheritance
 However, programming with virtual functions is
definitely is useful
 It is one of the most complex topics in C++

12/08/21 QAU-IT-2010-Fall 35
Conversions : Nonrelated Classes
 C++ supports the concept of strong typing
 Two different classes are nonrelated if neither of them
serves as a direct or indirect base class for another class
 expressions , assignments and function arguments

 objects used as targets of messages

 Conversion constructors
 Casts Between Pointers (or References)
 The rules for implicit conversions apply only to values and

not to references or to pointers: Type casting is required


 Conversion operators

12/08/21 QAU-IT-2010-Fall 36
Safe and Unsafe Conversions
 Moving data from larger to smaller variable
 Moving data from smaller to larger variable
 C++ defers to the programmer in evaluating the situation
 Assigning Base class object to derived class object
 Assigning derived class object to Base class object
 Derived class object can not be assigned to base class
object
 Base class object can be assigned to derived class object
 Use conversion constructor & assignment op overloaded
 Type casting uses constructor

12/08/21 QAU-IT-2010-Fall 37
Safe and Unsafe Conversions

12/08/21 QAU-IT-2010-Fall 38
Safe and Unsafe Conversions

12/08/21 QAU-IT-2010-Fall 39
Conversions of Pointers and
References to Objects
 In this topic everything about pointers applies to
references as well
 The conversion from a Base pointer (or reference) to a
Derived pointer (reference) is not safe
 Derived class pointer can be assigned to base class
 Using cast operator, unsafe conversion can be performed
 Pointer of Derived in pointer of Base is restrictive
 Pointers of a specific class must not point to objects of
classes not related to this one by inheritance

12/08/21 QAU-IT-2010-Fall 40
Conversions of Pointer and
Reference Arguments
 If formal and actual parameters are not related through
inheritance, syntax error will be result
 If parameters are passed by value, conversion is
possible if provided
 But for pointers and references, type casting is needed
 Derived class pointer can be passed where Base class
pointer is required
 Base class pointer can not be passed where Derived
class pointer is required

12/08/21 QAU-IT-2010-Fall 41
Virtual Functions: Another New Idea
 Object name and type association concepts
 Compile time associations
 Early or Static binding
 The name that the compiler knows is a concatenation of
the name of the class to which the function belongs, the
function identifier, the return type, and the types of its
parameters
 As a result, each function name is actually unique for the
compiler
 This technique is known as name mangling

12/08/21 QAU-IT-2010-Fall 42
Virtual Functions-Binding time
 The class name of the object is known at compile time
and cannot change during execution
 Static binding is standard in modern languages such as
C++, C, Java, Ada, Pascal
 It was introduced to improve performance
 Static binding could be successfully used to enforce type
checking at compile time
 Dynamic or late binding
 What possible advantages might it bring?

12/08/21 QAU-IT-2010-Fall 43
Virtual Functions-Binding terms
 The compiler binds the function name to a particular
function
 We want this binding to take place at run time. This is
why it is called run-time binding
 We want this binding to take place later than during the
compile time. This is why it is called late rather than
early binding
 This binding to allows the same function name to take
on different meanings depending on the nature of the
object used. So it is called dynamic binding

12/08/21 QAU-IT-2010-Fall 44
Polymorphism
 The ability of the function name in a function call to take
different meanings is called polymorphism("many
forms")
 Assigning the meaning to the method call at run time
depending on the actual type of the object that is the
target of the message
 Dynamic binding is not an issue specific to object-
oriented programming
 Non-Object Oriented approach

12/08/21 QAU-IT-2010-Fall 45
Polymorphism
 Object oriented approach
 Define a Base class with one data member “kind”
 Code a Write method in both derived classes
 Code a Read method in both derived classes
 Use “kind” to call proper method by type-casting
 Data and operations are bound together
 Work is pushed to server classes
 The source code is longer in object-oriented solution

12/08/21 QAU-IT-2010-Fall 46
Dynamic Binding: Virtual Functions
 Keyword virtual creates the run-time type resolution
property for a message sent to a derived type object
 Implement the function with the same name in the base
class and in each of the derived classes
 Pointer of the derived class will be stored in Base class
pointer
 The type of the object will be decided on run time
 If virtual function is called on object then there is static
binding
 Function signatures should be same in base and derived

12/08/21 QAU-IT-2010-Fall 47
Dynamic and Static Binding
 For the base pointer pointing to a base object, only
those methods defined in the base class can be called
 A derived pointer pointing to a derived object can reach
methods defined in the derived class and methods
inherited from the base class
 Methods redefined in the derived class hide methods
defined in the base class (with the same or different
signature, virtual or not) from the derived class pointer

12/08/21 QAU-IT-2010-Fall 48
Virtual function call
 A base pointer pointing to a derived object can reach
only those methods defined in the base class with one
exception:
 If the function is redefined in the derived class as

virtual
 it is the derived class function that the base pointer

invokes using dynamic binding, not the base class


function

12/08/21 QAU-IT-2010-Fall 49
Pure Virtual Functions
 Base virtual functions may have no job to do because
they have no meaning within the application (mostly)
 Their job is just to define the interface as a standard for
its derived classes
 This is why virtual functions are introduced in the first
place
 Some time it is possible that Base class can not create
meaningful objects
 C++ makes it possible through the use of pure virtual
functions and abstract classes

12/08/21 QAU-IT-2010-Fall 50
Pure Virtual Functions
 An abstract class is a class with at least one pure virtual
function
 No C++ keywords for pure virtual functions and abstract
classes: =0; is used after function declaration
 A pure virtual function has no implementation
 Derived class must implement the pure virtual functions
 If it does not implement, it becomes abstract as well
 An abstract class is a C++ class in all regards:
 it can have data members
 regular non-pure functions, including virtual functions

12/08/21 QAU-IT-2010-Fall 51
Virtual Functions: Destructors
 When the delete operator is invoked, the destructor is
called and the object is destroyed
 Which destructor is called?
 When a base pointer points to a derived class object,
the base class destructor is called
 So make destructor of the Base class as virtual
 This will prevent memory leaks and all constructor will
be called

12/08/21 QAU-IT-2010-Fall 52

You might also like