Another Way to Define A Class - Inheritance - PowerPoint PPT Presentation

1 / 72
About This Presentation
Title:

Another Way to Define A Class - Inheritance

Description:

Title: C++ Inheritance Author: Barbara Hecker Last modified by: bhecker Created Date: 10/27/2001 9:41:10 PM Document presentation format: On-screen Show – PowerPoint PPT presentation

Number of Views:81
Avg rating:3.0/5.0
Slides: 73
Provided by: BarbaraH154
Category:

less

Transcript and Presenter's Notes

Title: Another Way to Define A Class - Inheritance


1
  • Another Way to Define A Class - Inheritance

2
Inheritance Concept
class Rectangle private int width,
length public void set(int w, int l)
int area()
Polygon
Rectangle
Triangle
class Polygon private int width,
length public void set(int w, int l)
class Triangle private int width,
length public void set(int w, int l)
int area()
3
Inheritance Concept
class Polygon protected int width,
length public void set(int w, int l)
Polygon
Rectangle
Triangle
class Rectangle protected int width,
length public void set(int w, int l)
int area()
class Rectangle public Polygon public int
area()
4
Inheritance Concept
class Polygon protected int width,
length public void set(int w, int l)
Polygon
Rectangle
Triangle
class Triangle protected int width,
length public void set(int w, int l)
int area()
class Triangle public Polygon public int
area()
5
Inheritance Concept
class Point protected int x,
y public void set(int a, int b)
x y
Point
Circle
3D-Point
x y r
x y z
class Circle public Point private double
r
class 3D-Point public Point private int
z
6
Inheritance Concept
  • Augmenting the original class
  • Specializing the original class

Polygon
Point
Rectangle
Triangle
Circle
3D-Point
real imag
ComplexNumber
RealNumber
ImaginaryNumber
imag
real
7
Why Inheritance ?
  • Inheritance is a mechanism for
  • building class types from existing class types
  • defining new class types to be a
  • specialization
  • augmentation
  • of existing types

8
Define a Class Hierarchy
  • Syntax
  • class DerivedClassName access-level
    BaseClassName
  • where
  • access-level specifies the type of derivation
  • private by default, or
  • public
  • Any class can serve as a base class
  • Thus a derived class can also be a base class

9
Class Derivation
Point
class Point protected int x, y public
void set(int a, int b)
3D-Point
Sphere
class 3D-Point public Point private double
z
class Sphere public 3D-Point private double
r
Point is the base class of 3D-Point, while
3D-Point is the base class of Sphere
10
What to inherit?
  • In principle, every member of a base class is
    inherited by a derived class
  • just with different access permission

11
Access Control Over the Members
  • Two levels of access control over class members
  • class definition
  • inheritance type

class Point protected int x, y public void
set(int a, int b)
class Circle public Point
12
Access Rights of Derived Classes
Type of Inheritance
private protected public
private private private private
protected private private protected
public private protected public
Access Control for Members
  • The type of inheritance defines the minimum
    access level for the members of derived class
    that are inherited from the base class
  • With public inheritance, the derived class follow
    the same access permission as in the base class
  • With protected inheritance, only the public
    members inherited from the base class can be
    accessed in the derived class as protected
    members
  • With private inheritance, none of the members of
    base class is accessible by the derived class

13
Class Derivation
class daughter public mother private
double a public void foo ( )
mother
daughter
son
class mother protected int x,
y public void set(int a, int
b) private int z
void daughter foo ( ) x y 20 set(5,
10) coutltltvalue of a ltltaltltendl z 100
// error, a private member
daughter can access 3 of the 4 inherited members
14
Class Derivation
class son protected mother private double
b public void foo ( )
mother
daughter
son
class mother protected int x,
y public void set(int a, int
b) private int z
void son foo ( ) x y 20 // error, not
a public member set(5, 10) coutltltvalue of b
ltltbltltendl z 100 // error, not a public
member
son can access only 1 of the 4 inherited member
15
What to inherit?
  • In principle, every member of a base class is
    inherited by a derived class
  • just with different access permission
  • However, there are exceptions for
  • constructor and destructor
  • operator() member
  • friends
  • Since all these functions are class-specific

16
Constructor Rules for Derived Classes
  • The default constructor and the destructor of
    the base class are always called when a new
    object of a derived class is created or
    destroyed.

class A public A ( ) coutltlt
Adefaultltltendl A (int a)
coutltltAparameterltltendl
class B public A public B (int a)
coutltltBltltendl
output
Adefault B
B test(1)
17
Constructor Rules for Derived Classes
  • You can also specify an constructor of the base
    class other than the default constructor

DerivedClassCon ( derivedClass args )
BaseClassCon ( baseClass args )
DerivedClass constructor body
class A public A ( ) coutltlt
Adefaultltltendl A (int a)
coutltltAparameterltltendl
class C public A public C (int a)
A(a) coutltltCltltendl
output
Aparameter C
C test(1)
18
Define its Own Members
The derived class can also define its own
members, in addition to the members inherited
from the base class
class Point protected int x, y public
void set(int a, int b)
x y
Point
x y r
Circle
protected int x, y private double
r public void set(int a, int b) void
set_r(double c)
class Circle public Point private double
r public void set_r(double c)
19
Even more
  • A derived class can override methods defined in
    its parent class. With overriding,
  • the method in the subclass has the identical
    signature to the method in the base class.
  • a subclass implements its own version of a base
    class method.

class A protected int x, y
public void print () coutltltFrom Altltendl
class B public A public void print
() coutltltFrom Bltltendl
20
Access a Method
class Point protected int x,
y public void set(int a, int b) xa
yb void foo () void print()
class Circle public Point private double
r public void set (int a, int b, double c)
Point set(a, b) //same name function
call r c void print()
Circle C C.set(10,10,100) // from class
Circle C.foo () // from base class
Point C.print() // from class Circle
Point A A.set(30,50) // from base class
Point A.print() // from base class Point
21
Putting Them Together
  • Time is the base class
  • ExtTime is the derived class with public
    inheritance
  • The derived class can
  • inherit all members from the base class, except
    the constructor
  • access all public and protected members of the
    base class
  • define its private data member
  • provide its own constructor
  • define its public member functions
  • override functions inherited from the base class

22
class Time Specification
// SPECIFICATION FILE ( time.h)
  • class Time
  • public
  • void Set ( int h, int m, int s )
  • void Increment ( )
  • void Write ( ) const
  • Time ( int initH, int initM, int initS )
    // constructor
  • Time ( ) // default
    constructor
  • protected
  • int hrs
  • int mins
  • int secs

23

Class Interface Diagram
Time class
Set
Protected data hrs mins secs
Increment
Write
Time
Time
24
Derived Class ExtTime
  • // SPECIFICATION FILE ( exttime.h)
  • include time.h
  • enum ZoneType EST, CST, MST, PST, EDT, CDT,
    MDT, PDT
  • class ExtTime public Time
  • // Time is the base class and use public
    inheritance
  • public
  • void Set ( int h, int m, int s,
    ZoneType timeZone )
  • void Write ( ) const //overridden
  • ExtTime (int initH, int initM, int initS,
    ZoneType initZone )
  • ExtTime () // default constructor
  • private

25

Class Interface Diagram
ExtTime class
Set
Set
Protected data hrs mins secs
Increment
Increment
Write
Write
Time
ExtTime
Time
ExtTime
Private data zone
26
Implementation of ExtTime
Default Constructor
  • ExtTime ExtTime ( )
  • zone EST

ExtTime et1
et1
hrs 0 mins 0 secs 0 zone EST
The default constructor of base class, Time(), is
automatically called, when an ExtTime object is
created.
27
Implementation of ExtTime
Another Constructor
  • ExtTime ExtTime (int initH, int initM, int
    initS, ZoneType initZone)
  • Time (initH, initM, initS)
  • // constructor initializer
  • zone initZone

ExtTime et2 new ExtTime(8,30,0,EST)
28
Implementation of ExtTime
  • void ExtTime Set (int h, int m, int s,
    ZoneType timeZone)
  • Time Set (hours, minutes, seconds) //
    same name function call
  • zone timeZone

void ExtTime Write ( ) const // function
overriding string zoneString8
EST, CST, MST, PST, EDT, CDT,
MDT, PDT Time Write ( ) cout
ltlt ltltzoneStringzoneltltendl
29
Working with ExtTime
  • include exttime.h
  • int main()
  • ExtTime thisTime ( 8, 35, 0, PST )
  • ExtTime thatTime //
    default constructor called
  • thatTime.Write( ) // outputs 000000
    EST
  • thatTime.Set (16, 49, 23, CDT)
  • thatTime.Write( ) // outputs 164923
    CDT
  • thisTime.Increment ( )
  • thisTime.Increment ( )
  • thisTime.Write ( ) // outputs 083502
    PST

30
Inheritance Summary
  • Inheritance is a mechanism for defining new class
    types to be a specialization or an augmentation
    of existing types.
  • In principle, every member of a base class is
    inherited by a derived class with different
    access permissions, except for the constructors

31
More C Concepts
  • Operator overloading
  • Friend Function
  • This Operator
  • Inline Function

32
Review
  • There are different types of member functions in
    the definition of a class
  • Accessor
  • int Str get_length()
  • implementor/worker
  • void Rectangle set(int, int)
  • helper
  • void Date errmsg(const char msg)
  • constructor
  • Account Account()
  • Account Account(const Account a)
  • Account Account(const char person)
  • destructor
  • Account Account()

33
Operator overloading
  • Programmer can use some operator symbols to
    define special member functions of a class
  • Provides convenient notations for object behaviors

34
Why Operator Overloading
int i, j, k // integers float m, n, p //
floats k i j // integer addition and
assignment p m n // floating addition and
assignment
The compiler overloads the operator for
built-in integer and float types by default,
producing integer addition with ij, and floating
addition with mn.
We can make object operation look like
individual int variable operation, using operator
functions Date a,b,c c a b
35
Operator Overloading Syntax
  • Syntax is

Examples operator operator- operator operator/
operator_at_(argument-list)
--- operator is a function
--- _at_ is one of C operator symbols (, -, ,
etc..)
36
Example of Operator Overloading
  • class CStr
  • char pData
  • int nLength
  • public
  • //
  • void cat(char s)
  • //
  • friend CStr operator(CStr str1, CStr str2)
  • friend CStr operator(CStr str, char s)
  • friend CStr operator(char s, CStr str)
  • //accessors
  • char get_Data()
  • int get_Len()

void CStrcat(char s) int n char
pTemp nstrlen(s) if (n0) return
pTempnew charnnLength1 if (pData)
strcpy(pTemp,pData) strcat(pTemp,s)
pDatapTemp nLengthn
37
The Addition () Operator
  • CStr operator(CStr str1, CStr str2)
  • CStr new_string(str1)
  • //call the copy constructor to initialize an
    entirely new CStr object with the first operand
  • new_string.cat(str2.get_Data())
  • //concatenate the second operand onto the end
    of new_string
  • return new_string
  • //call copy constructor to create a copy of
    the return value new_string

new_string
str1 strlen(str1)
strcat(str1,str2) strlen(str1)strlen(str2)
38
How does it work?
  • CStr first(John)
  • CStr last(Johnson)
  • CStr name(firstlast)

CStr operator(CStr str1,CStr str2) CStr
new_string(str1) new_string.cat(str2.get()) re
turn new_string
John Johnson
name
Copy constructor
Temporary CStr object
39
Implementing Operator Overloading
  • Two ways
  • Implemented as member functions
  • Implemented as non-member or Friend functions
  • the operator function may need to be declared as
    a friend if it requires access to protected or
    private data
  • Expression obj1_at_obj2 translates into a function
    call
  • obj1.operator_at_(obj2), if this function is defined
    within class obj1
  • operator_at_(obj1,obj2), if this function is defined
    outside the class obj1

40
Implementing Operator Overloading
  1. Defined as a member function

class Complex ... public ...
Complex operator (const Complex op)
double real _real op._real,
imag _imag op._imag
return(Complex(real, imag)) ...
c ab
41
Implementing Operator Overloading
  1. Defined as a non-member function

class Complex ... public ...
double real() return _real //need
access functions double imag() return _imag
...
c ab
Complex operator (Complex op1, Complex op2)
double real op1.real()
op2.real(), imag op1.imag()
op2.imag() return(Complex(real, imag))
42
Implementing Operator Overloading
  1. Defined as a friend function

class Complex ... public ...
friend Complex operator ( const Complex ,
const Complex ) ...
c ab
Complex operator (Complex op1, Complex op2)
double real op1._real op2._real,
imag op1._imag op2._imag
return(Complex(real, imag))
43
What is Friend?
  • Friend declarations introduce extra coupling
    between classes
  • Once an object is declared as a friend, it has
    access to all non-public members as if they were
    public
  • Access is unidirectional
  • If B is designated as friend of A, B can access
    As non-public members A cannot access Bs
  • A friend function of a class is defined outside
    of that class's scope

44
More about Friend
  • The major use of friends is
  • to provide more efficient access to data members
    than the function call
  • to accommodate operator functions with easy
    access to private data members
  • Friends can have access to everything, which
    defeats data hiding, so use them carefully
  • Friends have permission to change the internal
    state from outside the class. Always recommend
    use member functions instead of friends to change
    state

45
Assignment Operator
  • Assignment between objects of the same type is
    always supported
  • the compiler supplies a hidden assignment
    function if you dont write your own one
  • same problem as with the copy constructor - the
    member by member copying
  • Syntax
  • class classoperator(const class arg)
  • //

46
Example Assignment for CStr class
Assignment operator for CStr CStr
operator(const CStr source)
  • CStr operator(const CStr source)
  • //... Do the copying
  • return this

47
Overloading stream-insertion and
stream-extraction operators
  • In fact, coutltlt or cingtgt are operator overloading
    built in C standard lib of iostream.h, using
    operator "ltlt" and "gtgt"
  • cout and cin are the objects of ostream and
    istream classes, respectively
  • We can add a friend function which overloads the
    operator ltlt

friend ostream operatorltlt (ostream ous, const
Date d)
48
Overloading stream-insertion and
stream-extraction operators
  • We can also add a friend function which overloads
    the operator gtgt

friend istream operatorgtgt (istream in, Date d)
istream operatorgtgt (istream in, Date d)
char mmddyy9 in gtgt mmddyy // check if
valid data entered if (d.set(mmddyy)) return
in coutltlt "Invalid date format "ltltdltltendl
exit(-1)
cin gtgt d1
49
The this pointer
  • Within a member function, the this keyword is a
    pointer to the current object, i.e. the object
    through which the function was called
  • C passes a hidden this pointer whenever a
    member function is called
  • Within a member function definition, there is an
    implicit use of this pointer for references to
    data members

this
Data member reference Equivalent
to pData this-gtpData nLength this-gtnLength
pData
nLength
CStr object (this)
50
Inline functions
  • An inline function is one in which the function
    code replaces the function call directly.
  • Inline class member functions
  • if they are defined as part of the class
    definition, implicit
  • if they are defined outside of the class
    definition, explicit, I.e.using the keyword,
    inline.
  • Inline functions should be short (preferable
    one-liners).
  • Why? Because the use of inline function results
    in duplication of the code of the function for
    each invocation of the inline function  

51
Example of Inline functions
  • class CStr
  • char pData
  • int nLength
  • public
  • char get_Data(void) return pData
    //implicit inline function
  • int getlength(void)
  • inline void CStrgetlength(void) //explicit
    inline function
  • return nLength
  •  
  • int main(void)

Inline functions within class declarations
Inline functions outside of class declarations
In both cases, the compiler will insert the code
of the functions get_Data() and getlength()
instead of generating calls to these functions
52
Inline functions
  • An inline function can never be located in a
    run-time library since the actual code is
    inserted by the compiler and must therefore be
    known at compile-time.
  • It is only useful to implement an inline function
    when the time which is spent during a function
    call is long compared to the code in the
    function.

53
Overloading Summary
  • Operator overloading provides convenient
    notations for object behaviors
  • There are three ways to implement operator
    overloading
  • member functions
  • normal non-member functions
  • friend functions

54
Polymorphism
55
Object-Oriented Concept
  • Encapsulation
  • ADT, Object
  • Inheritance
  • Derived object
  • Polymorphism
  • Each object knows what it is

56
Polymorphism An Introduction
  • noun, the quality or state of being able to
    assume different forms - Webster
  • An essential feature of an OO Language
  • It builds upon Inheritance

57
Before we proceed.
  • Inheritance Basic Concepts
  • Class Hierarchy
  • Code Reuse, Easy to maintain
  • Type of inheritance public, private
  • Function overriding

58

Class Interface Diagram
Time class
ExtTime class
Set
Set
Protected data hrs mins secs
Increment
Increment
Write
Write
Time
ExtTime
Time
ExtTime
Private data zone
59
Why Polymorphism?--Review Time and ExtTime
Example by Inheritance
  • void Print (Time someTime ) //pass an object
    by value
  • cout ltlt Time is
  • someTime.Write ( )
  • cout ltlt endl
  • CLIENT CODE
  • Time startTime ( 8, 30, 0 )
  • ExtTime endTime (10, 45, 0, CST)
  • Print ( startTime )
  • Print ( endTime )

// Time write()
OUTPUT Time is 083000 Time is
104500
60
Static Binding
  • When the type of a formal parameter is a parent
    class, the argument used can be
  • the same type as the formal parameter,
  • or,
  • any derived class type.
  • Static binding is the compile-time determination
    of which function to call for a particular object
    based on the type of the formal parameter
  • When pass-by-value is used, static binding occurs

61
Polymorphism An Introduction
  • noun, the quality or state of being able to
    assume different forms - Webster
  • An essential feature of an OO Language
  • It builds upon Inheritance
  • Allows run-time interpretation of object type for
    a given class hierarchy
  • Also Known as Late Binding
  • Implemented in C using virtual functions

62
Dynamic Binding
  • Is the run-time determination of which function
    to call for a particular object of a derived
    class based on the type of the argument
  • Declaring a member function to be virtual
    instructs the compiler to generate code that
    guarantees dynamic binding
  • Dynamic binding requires pass-by-reference

63
Virtual Member Function
  • // SPECIFICATION FILE ( time.h )
  • class Time
  • public
  • . . .
  • virtual void Write ( ) // for
    dynamic binding
  • virtual Time() // destructor
  • private
  • int hrs
  • int mins
  • int secs

64
This is the way we like to see
  • void Print (Time someTime )
  • cout ltlt Time is
  • someTime-gtWrite ( )
  • cout ltlt endl

OUTPUT Time is 083000 Time is
104500 CST
CLIENT CODE Time startTime( 8, 30,
0 ) ExtTime endTime(10, 45, 0, CST) Time
timeptr timeptr startTime Print ( timeptr )
timeptr endTime Print ( timeptr )
65
Virtual Functions
  • Virtual Functions overcome the problem of run
    time object determination
  • Keyword virtual instructs the compiler to use
    late binding and delay the object interpretation
  • How ?
  • Define a virtual function in the base class. The
    word virtual appears only in the base class
  • If a base class declares a virtual function, it
    must implement that function, even if the body is
    empty
  • Virtual function in base class stays virtual in
    all the derived classes
  • It can be overridden in the derived classes
  • But, a derived class is not required to
    re-implement a virtual function. If it does not,
    the base class version is used

66
Polymorphism Summary
  • When you use virtual functions, compiler store
    additional information about the types of object
    available and created
  • Polymorphism is supported at this additional
    overhead
  • Important
  • virtual functions work only with
    pointers/references
  • Not with objects even if the function is virtual
  • If a class declares any virtual methods, the
    destructor of the class should be declared as
    virtual as well.

67
Abstract Classes Pure Virtual Functions
  • Some classes exist logically but not physically.
  • Example Shape
  • Shape s // Legal but silly..!! Shapeless
    shape
  • Shape makes sense only as a base of some classes
    derived from it. Serves as a category
  • Hence instantiation of such a class must be
    prevented

class Shape //Abstract public //Pure
virtual Function virtual void draw() 0
  • A class with one or more pure virtual
    functions is an Abstract Class
  • Objects of abstract class cant be created

Shape s // error variable of an abstract class
68
Example
Shape
virtual void draw()
Circle
Triangle
public void draw()
public void draw()
69
  • A pure virtual function not defined in the
    derived class remains a pure virtual function.
  • Hence derived class also becomes abstract

class Circle public Shape //No draw() -
Abstractpublic void print() cout ltlt I am a
circle ltlt endl class Rectangle public Shape
public void draw() // Override
Shapedraw() cout ltlt Drawing Rectangle ltlt
endl
Rectangle r // Valid Circle c // error
variable of an abstract class
70
Pure virtual functions Summary
  • Pure virtual functions are useful because they
    make explicit the abstractness of a class
  • Tell both the user and the compiler how it was
    intended to be used
  • Note It is a good idea to keep the common code
    as close as possible to the root of you hierarchy

71
Summary ..continued
  • It is still possible to provide definition of a
    pure virtual function in the base class
  • The class still remains abstract and functions
    must be redefined in the derived classes, but a
    common piece of code can be kept there to
    facilitate reuse
  • In this case, they can not be declared inline

class Shape //Abstract public virtual void
draw() 0 // OK, not defined inline void
Shapedraw() cout ltlt Shape" ltlt endl
class Rectangle public Shape public
void draw() Shapedraw() //Reuse
cout ltltRectangleltlt endl
72
Polymorphism Summary
  • Polymorphism is built upon class inheritance
  • It allows different versions of a function to be
    called in the same manner, with some overhead
  • Polymorphism is implemented with virtual
    functions, and requires pass-by-reference
Write a Comment
User Comments (0)
About PowerShow.com