0% found this document useful (0 votes)
33 views45 pages

Class - Inheritance

The document discusses inheritance in C++. It defines inheritance as a mechanism for building class types from existing class types by defining new class types as specializations or augmentations of existing types. It provides examples of defining a class hierarchy using inheritance with syntax like "class DerivedClassName : access-level BaseClassName". A derived class inherits members from its base class but with different access permissions. A derived class can also define its own additional members.

Uploaded by

Desada
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views45 pages

Class - Inheritance

The document discusses inheritance in C++. It defines inheritance as a mechanism for building class types from existing class types by defining new class types as specializations or augmentations of existing types. It provides examples of defining a class hierarchy using inheritance with syntax like "class DerivedClassName : access-level BaseClassName". A derived class inherits members from its base class but with different access permissions. A derived class can also define its own additional members.

Uploaded by

Desada
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 45

Class - Inheritance

1
Inheritance Concept
class Rectangle{
Polygon private:
int width, length;
public:
void set(int w, int l);
Rectangle Triangle int area();
}

class Polygon class Triangle{


{ private:
private: int width, length;
int width, length; public:
public: void set(int w, int l);
void set(int w, int l); int area();
} } 2
Inheritance Concept
class Polygon
Polygon {
protected:
int width, length;
public:
void set(int w, int l);
Rectangle Triangle }
class Rectangle{
protected:
class Rectangle : public Polygon int width, length;
{ public:
public: int area(); void set(int w, int l);
} int area();
} 3
Inheritance Concept
class Polygon
Polygon {
protected:
int width, length;
public:
void set(int w, int l);
Rectangle Triangle }
class Triangle{
protected:
class Triangle : public Polygon int width, length;
{ public:
public: int area(); void set(int w, int l);
} int area();
} 4
Inheritance Concept
x
class Point
Point y {
protected:
int x, y;
Circle 3D-Point public:
x x void set(int a, int b);
y y
r z }

class Circle : public Point class 3D-Point: public Point


{ {
private: private:
double r; int z;
} }
5
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

6
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

7
Class Derivation
Point class Point{
protected:
int x, y;
3D-Point public:
void set(int a, int b);
}
Sphere

class 3D-Point : public Point{ class Sphere : public 3D-Point{


private: double z; private: double r;
…… ……
} }

Point is the base class of 3D-Point, while 3D-Point is the base class of Sphere
8
What to inherit?

• In principle, every member of a base class


is inherited by a derived class
– just with different access permission

9
Access Control Over the Members
• Two levels of access control
base class/ superclass/ over class members
parent class – class definition
– inheritance type
derive from

members goes to

class Point{
protected: int x, y;
public: void set(int a, int b);
derived class/ subclass/ }
child class class Circle : public Point{
……
}
10
Class Derivation
class daughter : public mother{
mother private:
double a;
public:
daughter son void foo ( );
}
class mother{
protected: void daughter :: foo ( ){
int x, y; x = y = 20;
public: set(5, 10);
void set(int a, int b); cout<<“value of a ”<<a<<endl;
private: z = 100; // error, a private member
int z; }
}
daughter can access 3 of the 4 inherited members
11
Class Derivation
class son : protected mother{
mother private:
double b;
public:
daughter son void foo ( );
}
class mother{
protected: void son :: foo ( ){
int x, y; x = y = 20; // error, not a public member
public: set(5, 10);
void set(int a, int b); cout<<“value of b ”<<b<<endl;
private: z = 100; // error, not a public member
int z; }
}
son can access only 1 of the 4 inherited member
12
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
Since all these functions are class-specific

13
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 { class B : public A


public: {
A() public:
{cout<< “A:default”<<endl;} B (int a)
A (int a) {cout<<“B”<<endl;}
{cout<<“A:parameter”<<endl;} }
}

output: A:default
B test(1); B 14
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 { class C : public A


public: {
A() public:
{cout<< “A:default”<<endl;} C (int a) : A(a)
A (int a) {cout<<“C”<<endl;}
{cout<<“A:parameter”<<endl;} }
}
output: A:parameter
C test(1); C 15
Define its Own Members
The derived class can also define
its own members, in addition to
class Point{
the members inherited from the
base class protected:
int x, y;
x
Point y
public:
void set(int a, int b);
x }
y Circle
r protected:
class Circle : public Point{ int x, y;
private: private:
double r; double r;
public: public:
void set_r(double c); void set(int a, int b);
} void set_r(double c); 16
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: class B : public A
int x, y; {
public: public:
void print () void print ()
{cout<<“From A”<<endl;} {cout<<“From B”<<endl;}
} }
17
Access a Method
class Point
class Circle : public Point{
{
private: double r;
protected:
public:
int x, y;
void set (int a, int b, double c) {
public:
Point :: set(a, b); //same name function call
void set(int a, int b)
r = c;
{x=a; y=b;}
}
void foo ();
void print(); }
void print();
}
Circle C;
Point A; C.set(10,10,100); // from class Circle
A.set(30,50); // from base class Point C.foo (); // from base class Point
A.print(); // from base class Point C.print(); // from class Circle
18
Putting Them Together
• Time is the base class
• ExtTime is the derived class with
Time public inheritance
• The derived class can
– inherit all members from the base
class, except the constructor
– access all public and protected
ExtTime 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
19
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 ;
};

20
Class Interface Diagram

Time class

Set
Protected data:
Increment
hrs
Write
mins

Time secs

Time

21
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 :
ZoneType zone ; // added data member
};
22
Class Interface Diagram
ExtTime class

Set Set

Increment Increment Protected data:


hrs
Write Write
mins
ExtTime Time
secs
ExtTime Time
Private
data:
zone
23
Implementation of ExtTime

Default Constructor

ExtTime :: ExtTime ( ) ExtTime et1;


{
zone = EST ;
} et1
hrs = 0
The default constructor of mins = 0
base class, Time(), is secs = 0
automatically called, when zone = EST
an ExtTime object is created.
24
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 = 5000


new ExtTime(8,30,0,EST);
hrs = 8
et2 6000 mins = 30
5000
??? secs = 0
zone = EST 25
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 zoneString[8] =
{“EST”, “CST”, MST”, “PST”, “EDT”, “CDT”, “MDT”, “PDT”} ;

Time :: Write ( ) ;
cout <<‘ ‘<<zoneString[zone]<<endl;
}
26
Working with ExtTime
#include “exttime.h”
……
int main()
{
ExtTime thisTime ( 8, 35, 0, PST ) ;
ExtTime thatTime ; // default constructor called
thatTime.Write( ) ; // outputs 00:00:00 EST
thatTime.Set (16, 49, 23, CDT) ;
thatTime.Write( ) ; // outputs 16:49:23 CDT
thisTime.Increment ( ) ;
thisTime.Increment ( ) ;
thisTime.Write ( ) ; // outputs 08:35:02 PST
}
27
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

28
More C++ Concepts

• Operator overloading
• Friend Function
• This Operator
• Inline Function

29
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   30
Example of Inline functions
class CStr
{
char *pData;
int nLength;

public: Inline functions within class declarations

char *get_Data(void) {return pData; }//implicit inline function
int getlength(void);

};
inline void CStr::getlength(void) //explicit inline function
{
return nLength;
} Inline functions outside of class declarations

 
int main(void)
{
char *s;
int n;
CStr a(“Joe”);
s = a.get_Data();
In both cases, the compiler will insert the
n = b.getlength(); code of the functions get_Data() and
}
getlength() instead of generating calls to these
functions 31
Polymorphism

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

33
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

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

35
Class Interface Diagram
ExtTime class Time class

Set Set

Increment Increment Protected data:


hrs
Write Write
mins
ExtTime Time
secs
ExtTime Time
Private
data:
zone
36
Why Polymorphism?--Review:
Time and ExtTime Example by Inheritance
void Print (Time someTime ) //pass an object by value
{
cout << “Time is “ ;
someTime.Write ( ) ;
cout << endl ;
}

CLIENT CODE
// Time :: write()
Time startTime ( 8, 30, 0 ) ;
ExtTime endTime (10, 45, 0, CST) ;

Print ( startTime ) ;
Print ( endTime ) ;

OUTPUT
Time is 08:30:00
Time is 10:45:00

37
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

38
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
39
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

40
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 ;
};

41
This is the way we like to
see…
void Print (Time * someTime )
{
cout << “Time is “ ;
someTime->Write ( ) ;
cout << endl ;
} OUTPUT
CLIENT CODE Time is 08:30:00
Time is 10:45:00 CST
Time startTime( 8, 30, 0 ) ;
ExtTime endTime(10, 45, 0, CST) ;

Time *timeptr;
timeptr = &startTime;
Print ( timeptr ) ; Time::write()

timeptr = &endTime;
Print ( timeptr ) ; ExtTime::write()
42
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
43
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.
44
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

45

You might also like