OBJECTIVE
On completion of this period, you would be able to
know
• Necessity of Inheritance
• Relation between base class...
Inheritance

Acquiring the properties of one class to another
class is inheritance.

CM505.36

2
Necessity for inheritance
• Reusability
• We can derive a new class from an existing one
and add new features to it.

CM50...
Necessity for inheritance
•

Another major reason for inheriting is the
capability to express the inheritance relationship...
Relation between base class & derived class
•Inheritance is the process of creating a new class
called derived class from ...
Relation between base class and derived
class
Feature A
Base Class
(Existing Class)

Feature B
Feature C

Feature D
Derive...
Relation between base class and derived
class
•

The derived class inherits the features of the base
class A, B and C and ...
Relation between base class and derived
class
• A base class is also called
• parent class or
• super class

• A derived c...
Relation between base class and derived
class
DERIVED CLASS:
•The declaration of derived class is as that same
of ordinary...
Relation between base class and
derived class
DERIVED CLASS:
• The keyword class
• The name of the Derived class
•

A sing...
Relation between base class and derived
class
DERIVED CLASS:
•The type of derivation (private, public or
protected)

• The...
Pre requisite
Access control or visibility mode:
The three types of access control or visibility
modes are:

•

public

•
...
Syntax for defining a derived class
Syntax:
class derived_classname : visibilitymode
base_classname

{
………………
………………

Memb...
Relation between base class and derived
class
Syntax:
class derived_classname : visibilitymode
base_classname
{

………………
……...
Syntax for defining a derived class
contd..
•The colon indicates that the derived class name is
derived from the base clas...
Syntax for defining a derived class

contd..

Example:
class A
{
………………….}members of base class A
};
class x : public A
{
...
Access control or visibility mode
The three types of access control or visibility
modes are:
•

public

•

private

•

pro...
Access control or visibility mode
contd..

Public:

• The public derivation means that the derived
class can access the pu...
Access control or visibility mode
contd..
Public:
•The public members of the base class
becomes public members of the deri...
Access control or visibility mode
contd..
Public Member of a class:
• The members of a class, which are to be

visible out...
Access control or visibility mode
contd..
Public Member of a class:
• All the members and functions can be
declared in pub...
Access control or visibility mode
contd..
Public Member of a class:
• Either by function that belong to the class or
by th...
Access control or visibility mode
Public Member of a class

contd..

Example:
class person
{
public:
int age;
int get age(...
Access control or visibility mode
contd..
Private:

The private derivation means that the derived
class can access the pub...
Access control or visibility mode
contd..

Private:
•
The public, protected members of the base
class becomes private memb...
Access control or visibility mode
contd..
Private Member of a class:
•

The private member of a class have strict
access c...
Access control or visibility mode
Private Member of a class:
•

contd..

Thus providing a mechanism for preventing
acciden...
Access control or visibility mode
Private Member of a class:

contd..

•

Access control in c++ has objective of
reducing ...
Access control or visibility mode
Private Member of a class:

contd..

•The class should have at least one member

that is...
Access control or visibility mode
Private Member of a class:
Example:

contd..

class person
{
private:
int age;
int get a...
Access control (or) visibility mode
contd..

Protected:
•

The protected derivation means that the
derived class can acces...
Access control (or) visibility mode
contd..

Protected Member of a class :
•

The access control of the members is similar...
Access control (or) visibility mode
contd..
Protected Member of a class:
•The protected members of a class have strict
acc...
Access control (or) visibility mode
contd..

Protected Member of a class:
• Only the member functions of same class can
ac...
Access control (or) visibility mode
contd..
Protected Member of a class:
•

Information hiding is implemented.

•

The pro...
Access control (or) visibility mode
contd..
Protected Member of a class:
Example:
class person
{
protected:
int age;
int g...
Access control (or) visibility mode
contd..
Inheritance type

case class

derived class

private numbers
public numbers
pr...
Inheritance
The inheritance is classified as

•

Single inheritance

•

Multiple inheritance

•

Multilevel inheritance

•...
Inheritance
Single inheritance:

A single inheritance contains only one derived
class and one base class.
•

CM505.39

39
Single Inheritance

BASE CLASS

DERIVED CLASS

CM505.39

40
Multi level inheritance
• more than one level of inheritance

base class
level/1
Derived class
level/2

Derived class
CM50...
Multiple Inheritance
A derived class with several base
classes is known as multiple inheritance.

CM505.39

42
Multiple Inheritance

BASE CLASS 1

BASE CLASS 2

DERIVED CLASS

CM505.39

43
Hierarchical Inheritance

The properties of one class may be inheritance
by more than one class. This process is known
as ...
Hierarchical Inheritance

BASE CLASS

DERIVED CLASS

DERIVED CLASS

CM505.39

DERIVED CLASS

45
Hybrid Inheritance

The combination of multilevel & multiple
inheritance is know as hybrid inheritance.

CM505.39

46
Hybrid Inheritance

BASE CLASS 1

DERIVED CLASS1

BASE CLASS 2

DERIVED CLASS2

CM505.39

47
Types of Derivation
• The class can be derived in three visibility
modes
• public

• private
• protected

48
Public Derivation
• When a class is derived in the public mode
it does not change the mode of the
inherited members in the...
Private Derivation
• When a class is derived in the private
mode it changes the mode of the inherited
members in the deriv...
Protected Derivation
• When a class is derived in protected mode
it changes the mode of the inherited
members in the deriv...
C++ Syntax: public derivation
class DerivedClass: public BaseClass
{
A derived class.
private:
The colon operator means
in...
C++ Syntax: public derivation
class DerivedClass: public BaseClass
{
private:
the public derivation means
int y;
that obje...
C++ Syntax: public derivation
class BaseClass
{
private:
int x;
public:
void setX(int x_in) {x=x_in;}
int getX() {cout<<x;...
C++ Syntax: private derivation
• class DerivedClass: private BaseClass
• {
• private:
– int y;

• public:
– void setY(int ...
C++ Syntax: the „protected‟ keyword

• An object of a publicly derived class can
access the public methods of the base
cla...
Access Specifiers
Access
Specifier

Accessible
from own
class

Accessible Accessible
from derived from objects
class
from ...
Effect of inheritance on the visibility of member

58
C++ Syntax: inheriting destructors
• Constructors are not inherited. They are called implicitly
or explicitly by the child...
Advantages of Inheritance
• When one class is inherited from another
class the code that provides a behavior required
in t...
Advantages of Inheritance
• Code sharing can occur at several levels.
• For example,
• At a higher level , many users can ...
Advantages of Inheritance

• When multiple classes inherit from the same
base class, it guarantees that the behavior they
...
Advantages of Inheritance
• Inheritance permits the construction of reusable
software components.
• Using inheritance one ...
Advantages of Inheritance

• The development time in developing a system
will be reduced rapidly.

CM505.39

64
Inheritance
• Inheritance can be continuous
– Derived class can inherit from a base class
– The derived class can act as a...
CPS235:Inheritance

66
Inheritance
Features: a,b

a
b
Class A
Features: a,b,c
c

Features: a,b,d,e

d
e

Class B

Class C
Features: a,b,d,e,f

f
...
Inheritance and Encapsulation
• private member
– Is accessible only via the base class

• public member
– Is accessible ev...
Inheritance Concept
class Rectangle{
private:
int width, length;
public:
void set(int w, int
l);
int area();
};

Polygon

...
Inheritance Concept
Polygon

Rectangle

Triangle

class Rectangle: public
Polygon
{
public:
int area();
};
CPS235:Inherita...
Inheritance Concept
Polygon

Rectangle

Triangle

class Triangle :
public Polygon
{
public:
int area();
CPS235:Inheritance...
Inheritance Concept
x
y

Point

Circle
x
y
r

class Point
{
protected:
int x, y;
public:
void set(int a, int
b);
};

3D-Po...
Declaring Inheritance
• Syntax:
class DerivedClassName : access-level BaseClassName

where

– access-level specifies the t...
Class Derivation
Point

3D-Point

Sphere

class 3D-Point :
public Point{
private: double
z;
… …
};

class Point{
protected...
What to Inherit?
• In principle, every member of a base class
is inherited by a derived class
– just with different access...
Access Control Over the Members

members goes to

derive from

base class/ superclass/
parent class

derived class/ subcla...
Member Access Control
• There are 3 levels of member (data or methods) access control:
– public: members can be used by it...
Access Rights of Derived Classes
Type of Inheritance
Access Control
for Members

private

protected

public

private

priv...
Access Rights of Derived
Classes
• Take these classes as examples:

class
class
class
class
class

B
D_priv : private
D_pr...
protected vs. private
So why not always use protected instead of private?
– Because protected means that we have less enca...
Class Derivation Example
mother

daughter

son

class mother{
protected:
int x, y;
public:
void set(int a,
int b);
private...
Class Derivation Example
mother

daughter

son

class mother{
protected:
int x, y;
public:
void set(int a,
int b);
private...
Class Derivation Example
mother

daughter

granddaughter

son

grandson

class mother{
protected:
int x, y;
public:
void s...
Class Derivation Example
void granddaughter :: foo ( ){
x = y = 20;
//OK
set(5, 10);
//OK
cout<<“value of a ”<<a<<endl; //...
Class Derivation Example
mother

daughter

granddaughter

son

grandson

class mother{
protected:
int x, y;
public:
void s...
Class Derivation Example
void grandson:: foo ( ){
x = y = 20;
//ERROR: not accessible
set(5, 10);
//ERROR: not accessible
...
Encapsulation

class Figure
{
protected:
int x, y;
};

class Circle : public Figure
{
public:
int radius;
};
int main()
{
...
Encapsulation
class Figure
{
protected:
int x_, y_;
};
class Circle : public
Figure
{
private:
int radius_;
public:
Circle...
Encapsulation
class Figure
{
private:
int x_, y_;
};
class Circle : public
Figure
{
private:
int radius_;
public:
Circle(i...
Encapsulation
class Figure
{
private:
int x_, y_;
public:
void SetX(int x);
void SetY(int y);
};
void Figure::SetX(int x)
...
What to Inherit?
• In principle, every member of a base class
is inherited by a derived class
– just with different access...
Constructor Rules for Derived
Classes
• The default constructor and the destructor of the base
class are always called whe...
Constructor Rules for Derived
Classes
• You can also specify a constructor of the base class other than the
default constr...
What is the result?
class Figure
{
public:
Figure()
{
cout << "Figure
Constructorn";
}
~Figure()
{
cout << "Figure
Destruc...
Constructor Rules for Derived
Classes
• Base constructor is called before the
derived class constructor
• Destructors vice...
Calling the Base Class
constructor
class Figure
{
public:
Figure() {
cout << "Figure Constructorn";
}
~Figure() {
cout << ...
Calling the Base Class constructor
class Figure
{
private:
int x, y;
public:
Figure(int xVal, int
yVal):x(xVal), y(yVal)
{...
Define its Own Members
The derived class can also define
its own members, in addition to
the members inherited from the
ba...
Even more …
• A derived class can override methods defined in its
parent class. With overriding,
– the method in the subcl...
Access a Method
class Point
{
protected:
int x, y;
public:
void set(int a,
int b)
{x=a; y=b;}
void foo ();
void print();
}...
Putting It All Together
Time

Public

ExtTime

CPS235:Inheritance

• Time is the base class
• ExtTime is the derived class...
Time class example

CPS235:Inheritance

102
class Time
class Time
{
public:
Time () :hrs(0),mins(0),secs(0){}
Time (int h, int m, int s):hrs(h),mins(m),secs(s){}
void...
Class Interface Diagram
Time class
Set

Increment

Protected data:
hrs

Write
Time

mins
secs

Time

CPS235:Inheritance

1...
Derived Class ExtTime
enum ZoneType {EST, CST, MST, PST, EDT, CDT, MDT,
PDT } ;
class ExtTime : public Time // Time is the...
Class Interface Diagram
ExtTime class

Set
Increment

Set
Increment

Protected data:
hrs

Write

Write
mins

ExtTime
ExtTi...
Implementation of ExtTime
Default Constructor
ExtTime :: ExtTime ()
{
zone = EST ;
}

et1
hrs = 0
mins = 0
secs = 0
zone =...
Implementation of ExtTime
Another Constructor
ExtTime :: ExtTime (int h, int m, int s, ZoneType z):
Time (h, m, s),zone(z)...
Derived Class ExtTime
ExtTime :: ExtTime ():zone(EST){}
ExtTime :: ExtTime (int h, int m, int s, ZoneType z)
: Time (h, m,...
Using class ExtTime
int main()
{
ExtTime
ExtTime

thisTime ( 8, 35, 0, PST ) ;
thatTime ;

thatTime.Write( );

// prints 0...
Multiple Inheritance
#include <iostream>
class CPolygon {
protected:
int width, height;
public:
void set_values (int a, in...
Multiple Inheritance
class CRectangle: public CPolygon, public COutput {
public:
int area ()
{ return (width * height); }
...
Ambiguities in Multiple
Inheritance
• See code examples

CPS235:Inheritance

113
Friend functions
• A friend function of a class is defined outside that class's
scope, yet has the right to access the non...
Example of friend functions
class beta; //req for frifunc declaration
class alpha
{
private:
int data;
public:
A class can...
Example of friend functions
int frifunc(alpha a, beta b)
{
return (a.data + b.data);
}
void main()
{
alpha aa;
beta bb;
co...
friend classes
• The member functions of a class can all be made friends
at the same time when you make the entire class a...
friend classes
class beta;
class alpha
{
private:
int data;
public:
alpha():data(3) {}
friend class beta; //friend class d...
friend classes
void main()
{
alpha aa;
beta bb;
bb.func(aa);
getch();
}

CPS235:Inheritance

119
Class member functions as
friends
class CSquare;
class CRectangle {
int width, height;
public:
int area ()
{return (width ...
Class member functions as
friends
void CRectangle::convert (CSquare a) {
width = a.side;
height = a.side;
}
int main () {
...
Summary (friends)
• Even though the prototypes for friend functions appear in
the class definition, friends are not member...
Exercise
• Consider a publishing company that markets both book and audiocassette versions of its work
• Create a class “p...
Compulsory Reading
• Deitel and Deitel (5th edition)
– Topic: 10.3. Composition: Objects as
Members of Classes
– Topic: 10...
Upcoming SlideShare
Loading in …5
×

Inheritance concepts

1,151 views

Published on

Published in: Business, Sports
0 Comments
3 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,151
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
80
Comments
0
Likes
3
Embeds 0
No embeds

No notes for slide

Inheritance concepts

  1. 1. OBJECTIVE On completion of this period, you would be able to know • Necessity of Inheritance • Relation between base class and derived class CM505.36 1
  2. 2. Inheritance Acquiring the properties of one class to another class is inheritance. CM505.36 2
  3. 3. Necessity for inheritance • Reusability • We can derive a new class from an existing one and add new features to it. CM505.36 3
  4. 4. Necessity for inheritance • Another major reason for inheriting is the capability to express the inheritance relationship which ensure the closeness with the real world. • And one of the other reason is transitive nature. CM505.36 4
  5. 5. Relation between base class & derived class •Inheritance is the process of creating a new class called derived class from the existing class called base class. •The derived class inherits all the capabilities of the base class.The base class remains unchanged. CM505.36 5
  6. 6. Relation between base class and derived class Feature A Base Class (Existing Class) Feature B Feature C Feature D Derived Class (New Class) Defined In Derived class Feature A Feature B Feature C Fig .1 CM505.36 Derived in base Class and also Accessible from Derived class 6
  7. 7. Relation between base class and derived class • The derived class inherits the features of the base class A, B and C and adds its own features D. • The arrow in the diagram symbolizes derived from. CM505.36 7
  8. 8. Relation between base class and derived class • A base class is also called • parent class or • super class • A derived class is also called • child class or • subclass. • A derived class may itself be base class from which the additional classes are derived. CM505.36 8
  9. 9. Relation between base class and derived class DERIVED CLASS: •The declaration of derived class is as that same of ordinary class. •A derived class contains of the following components CM505.36 9
  10. 10. Relation between base class and derived class DERIVED CLASS: • The keyword class • The name of the Derived class • A single colon CM505.36 10
  11. 11. Relation between base class and derived class DERIVED CLASS: •The type of derivation (private, public or protected) • The name of the base or parent class • The reminder of the class definition CM505.36 11
  12. 12. Pre requisite Access control or visibility mode: The three types of access control or visibility modes are: • public • private • protected CM505.37to38 12
  13. 13. Syntax for defining a derived class Syntax: class derived_classname : visibilitymode base_classname { ……………… ……………… Members of derived class }; CM505.37to38 13
  14. 14. Relation between base class and derived class Syntax: class derived_classname : visibilitymode base_classname { ……………… ……………… Members of derived class }; CM505.37to38 14
  15. 15. Syntax for defining a derived class contd.. •The colon indicates that the derived class name is derived from the base class name. •The visibility mode is optional.i.e it may be public or private. • The default visibility mode specifies the features are private. CM505.37to38 15
  16. 16. Syntax for defining a derived class contd.. Example: class A { ………………….}members of base class A }; class x : public A { ……………}members of derived class X }; CM505.37to38 16
  17. 17. Access control or visibility mode The three types of access control or visibility modes are: • public • private • protected CM505.37to38 17
  18. 18. Access control or visibility mode contd.. Public: • The public derivation means that the derived class can access the public and protected members of the base class but not the private members of base class CM505.37to38 18
  19. 19. Access control or visibility mode contd.. Public: •The public members of the base class becomes public members of the derived access specified for inherited members in the derived class. CM505.37to38 19
  20. 20. Access control or visibility mode contd.. Public Member of a class: • The members of a class, which are to be visible outside the class . • Public members should be declared in public section only. CM505.37to38 20
  21. 21. Access control or visibility mode contd.. Public Member of a class: • All the members and functions can be declared in public section • they can be accessed without any restriction from any where in the program. CM505.37to38 21
  22. 22. Access control or visibility mode contd.. Public Member of a class: • Either by function that belong to the class or by those external to the class. CM505.37to38 22
  23. 23. Access control or visibility mode Public Member of a class contd.. Example: class person { public: int age; int get age() { } }; CM505.37to38 23
  24. 24. Access control or visibility mode contd.. Private: The private derivation means that the derived class can access the public and protected members of the base class. CM505.37to38 24
  25. 25. Access control or visibility mode contd.. Private: • The public, protected members of the base class becomes private members of derived class. •i.e the inheritance becomes private in the derived class. •They cannot be inherited further. CM505.37to38 25
  26. 26. Access control or visibility mode contd.. Private Member of a class: • The private member of a class have strict access control. • Only the member functions of the same class can access these members. • The private members of a class are inaccessible outside the class. CM505.37to38 26
  27. 27. Access control or visibility mode Private Member of a class: • contd.. Thus providing a mechanism for preventing accidental modifications of the data members. • Information hidden is implemented. • The private members can still accessed. CM505.37to38 27
  28. 28. Access control or visibility mode Private Member of a class: contd.. • Access control in c++ has objective of reducing the likelihood of bugs and enhancing consistency. CM505.37to38 28
  29. 29. Access control or visibility mode Private Member of a class: contd.. •The class should have at least one member that is not private. CM505.37to38 29
  30. 30. Access control or visibility mode Private Member of a class: Example: contd.. class person { private: int age; int get age() { } }; CM505.37to38 30
  31. 31. Access control (or) visibility mode contd.. Protected: • The protected derivation means that the derived class can access the public and private members of the base class. •public protected numbers the base class become protected numbers in the derived class. CM505.37to38 31
  32. 32. Access control (or) visibility mode contd.. Protected Member of a class : • The access control of the members is similar to that of private members. • Protected members has more significance in inheritance. CM505.37to38 32
  33. 33. Access control (or) visibility mode contd.. Protected Member of a class: •The protected members of a class have strict access these members. •Providing a mechanism for preventing accidental modifications of the data members. CM505.37to38 33
  34. 34. Access control (or) visibility mode contd.. Protected Member of a class: • Only the member functions of same class can access these members. • The protected members of a class are inaccessible outside the class. CM505.37to38 34
  35. 35. Access control (or) visibility mode contd.. Protected Member of a class: • Information hiding is implemented. • The protected members can still be accessed. CM505.37to38 35
  36. 36. Access control (or) visibility mode contd.. Protected Member of a class: Example: class person { protected: int age; int get age() { } }; CM505.37to38 36
  37. 37. Access control (or) visibility mode contd.. Inheritance type case class derived class private numbers public numbers private public protected not inherited private numbers Protected numbers private numbers private numbers public numbers protected numbers not inherited public numbers protected numbers private numbers public numbers protected numbers not inherited protected numbers CM505.37to38 protected numbers 37
  38. 38. Inheritance The inheritance is classified as • Single inheritance • Multiple inheritance • Multilevel inheritance • Hierarchical inheritance • Hybrid inheritance CM505.39 38
  39. 39. Inheritance Single inheritance: A single inheritance contains only one derived class and one base class. • CM505.39 39
  40. 40. Single Inheritance BASE CLASS DERIVED CLASS CM505.39 40
  41. 41. Multi level inheritance • more than one level of inheritance base class level/1 Derived class level/2 Derived class CM505.39 41
  42. 42. Multiple Inheritance A derived class with several base classes is known as multiple inheritance. CM505.39 42
  43. 43. Multiple Inheritance BASE CLASS 1 BASE CLASS 2 DERIVED CLASS CM505.39 43
  44. 44. Hierarchical Inheritance The properties of one class may be inheritance by more than one class. This process is known as Hierarchical Inheritance. CM505.39 44
  45. 45. Hierarchical Inheritance BASE CLASS DERIVED CLASS DERIVED CLASS CM505.39 DERIVED CLASS 45
  46. 46. Hybrid Inheritance The combination of multilevel & multiple inheritance is know as hybrid inheritance. CM505.39 46
  47. 47. Hybrid Inheritance BASE CLASS 1 DERIVED CLASS1 BASE CLASS 2 DERIVED CLASS2 CM505.39 47
  48. 48. Types of Derivation • The class can be derived in three visibility modes • public • private • protected 48
  49. 49. Public Derivation • When a class is derived in the public mode it does not change the mode of the inherited members in the derived class. The public members remain public and protected members remain protected for the derived class in public inheritance. 49
  50. 50. Private Derivation • When a class is derived in the private mode it changes the mode of the inherited members in the derived class. The public and protected members become the private members for the derived class. So the inherited members can be accessed only through the member functions of the derived class. 50
  51. 51. Protected Derivation • When a class is derived in protected mode it changes the mode of the inherited members in the derived class. The public and protected members become the protected members for the derived class in protected inheritance. So the inherited members can be accessed only through the member functions of the derived class. 51
  52. 52. C++ Syntax: public derivation class DerivedClass: public BaseClass { A derived class. private: The colon operator means int y; public: void setY(int y_in) {y=y_in;} int getY(){cout<<y;} } the derived class inherits from the base class 52
  53. 53. C++ Syntax: public derivation class DerivedClass: public BaseClass { private: the public derivation means int y; that objects of the derived class can access the public methods public: and attributes of the base class void setY(int y_in) This is the most usual type {y=y_in;} of derivation int getY() {cout<<y;} } 53
  54. 54. C++ Syntax: public derivation class BaseClass { private: int x; public: void setX(int x_in) {x=x_in;} int getX() {cout<<x;} } main() { BaseClass base_object; DerivedClass derived_object; base_object.setX(7); derived_object.setX(12); derived_object.setY(1); base_object.getX(); derived_object.getY(); derived_object.getX(); return 0; } class DerivedClass: public BaseClass { private: int y; Object of the derived public: class can access methods void setY(int y_in){y=y_in;} of the derived class int getY(){cout<<y;} and also methods of the } base class 54
  55. 55. C++ Syntax: private derivation • class DerivedClass: private BaseClass • { • private: – int y; • public: – void setY(int y_in); – int getY(); Another derived class - the private derivation means that objects of the derived class can‟t access the public methods and attributes of the base class - but the methods of the derived class can! This is the least common type • } 55
  56. 56. C++ Syntax: the „protected‟ keyword • An object of a publicly derived class can access the public methods of the base class, but not the private attributes • Changing the private keyword in the base class to protected makes the attributes available to derived classes 56
  57. 57. Access Specifiers Access Specifier Accessible from own class Accessible Accessible from derived from objects class from outside the class public Yes Yes Yes protected Yes Yes No private Yes No No 57
  58. 58. Effect of inheritance on the visibility of member 58
  59. 59. C++ Syntax: inheriting destructors • Constructors are not inherited. They are called implicitly or explicitly by the child constructor. • The compiler creates a default constructor (one with no arguments) and a default copy constructor (one with an argument which is a reference to the same type). • But if we want a constructor that will accept an int, we have to define it explicitly 59
  60. 60. Advantages of Inheritance • When one class is inherited from another class the code that provides a behavior required in the derived class need not have to be rewritten that is code be reused which increases reliability. CM505.39 60
  61. 61. Advantages of Inheritance • Code sharing can occur at several levels. • For example, • At a higher level , many users can use the same class. • At lower level, code can be shared by two or more classes. CM505.39 61
  62. 62. Advantages of Inheritance • When multiple classes inherit from the same base class, it guarantees that the behavior they inherit will be the same in all classes. CM505.39 62
  63. 63. Advantages of Inheritance • Inheritance permits the construction of reusable software components. • Using inheritance one can concentrate on understanding the portion of the new system. CM505.39 63
  64. 64. Advantages of Inheritance • The development time in developing a system will be reduced rapidly. CM505.39 64
  65. 65. Inheritance • Inheritance can be continuous – Derived class can inherit from a base class – The derived class can act as a base class and another class can inherit from it – If you change the base class, all derived classes also change – Any changes in the derived class do not change the base class – All features of the base class are available in the derived class • However, the additional features in the derived class are not available in the base class CPS235:Inheritance 65
  66. 66. CPS235:Inheritance 66
  67. 67. Inheritance Features: a,b a b Class A Features: a,b,c c Features: a,b,d,e d e Class B Class C Features: a,b,d,e,f f Class D CPS235:Inheritance 67
  68. 68. Inheritance and Encapsulation • private member – Is accessible only via the base class • public member – Is accessible everywhere (base class, derived class, othe classes) • protected member – Is accessible by the base class and derived classes
  69. 69. 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); }; CPS235:Inheritance 69 class Triangle{ private: int width, length; public: void set(int w, int l); int area(); };
  70. 70. Inheritance Concept Polygon Rectangle Triangle class Rectangle: public Polygon { public: int area(); }; CPS235:Inheritance 70 class Polygon { protected: int width, length; public: void set(int w, int l); }; class Rectangle{ protected: int width, length; public: void set(int w, int l); int area();
  71. 71. Inheritance Concept Polygon Rectangle Triangle class Triangle : public Polygon { public: int area(); CPS235:Inheritance }; 71 class Polygon { protected: int width, length; public: void set(int w, int l); }; class Triangle{ protected: int width, length; public: void set(int w, int l); int area();
  72. 72. Inheritance Concept x y Point Circle x y r class Point { protected: int x, y; public: void set(int a, int b); }; 3D-Point x y z class Circle : public Point { private: double r; }; CPS235:Inheritance class 3D-Point: public Point { private: int z; }; 72
  73. 73. Declaring Inheritance • Syntax: class DerivedClassName : access-level BaseClassName where – access-level specifies the type of derivation • private by default, or • public or • protected (used very rarely) CPS235:Inheritance 73
  74. 74. Class Derivation Point 3D-Point Sphere class 3D-Point : public Point{ private: double z; … … }; class Point{ protected: int x, y; public: void set(int a, int b); }; class Sphere : public 3D-Point{ private: double r; … … }; Point is the base class of 3D-Point, while 3D-Point is the base class CPS235:Inheritance 74 of Sphere
  75. 75. What to Inherit? • In principle, every member of a base class is inherited by a derived class – just with different access permission CPS235:Inheritance 75
  76. 76. Access Control Over the Members members goes to derive from base class/ superclass/ parent class derived class/ subclass/ child class CPS235:Inheritance • 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{ … … 76 };
  77. 77. Member Access Control • There are 3 levels of member (data or methods) access control: – public: members can be used by itself and the whole world; any function can access them – protected: methods (and friends) of itself and any derived class can use it – private: members can only be used by its own methods (and its friends) • We’ll study friend functions later • Without inheritance, private and protected have the same meaning • The only difference is that methods of a derived class can access protected members of a base class, but cannot access private members of a base class CPS235:Inheritance 77
  78. 78. Access Rights of Derived Classes Type of Inheritance Access Control for Members private protected public private private private private protected private protected protected public private protected public • 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 follows 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
  79. 79. Access Rights of Derived Classes • Take these classes as examples: class class class class class B D_priv : private D_prot : protected D_publ : public UserClass B B B { { { { { B /*...*/ }; /*...*/ }; /*...*/ }; /*...*/ }; b; /*...*/ }; • None of the derived classes can access anything that is private in B • In D_priv, the public and protected parts of B are private • In D_prot, the public and protected parts of B are protected • In D_publ, the public parts of B are public and the protected parts of B are protected (D_publ is-a-kind-of-a B) • class UserClass can access only the public parts of B, which "seals off" UserClass from B CPS235:Inheritance 79
  80. 80. protected vs. private So why not always use protected instead of private? – Because protected means that we have less encapsulation – All derived classes can access protected data members of the base class – Assume that later you decided to change the implementation of the base class having the protected data members – For example, we might want to represent address by a new class called Address instead of string – If the address data member is private, we can easily make this change – The class documentation does not need to be changed. – If it is protected, we have to go through all derived classes and change them – We also need to update the class documentation. CPS235:Inheritance 80
  81. 81. Class Derivation Example mother daughter son class mother{ protected: int x, y; public: void set(int a, int b); private: int z; }; class daughter : public mother{ private: double a; public: void foo ( ); }; void daughter :: foo ( ){ x = y = 20; set(5, 10); cout<<“value of a ”<<a<<endl; z = 100; // error, a private member }; daughter can access 3 of the 4 inherited members CPS235:Inheritance 81
  82. 82. Class Derivation Example mother daughter son class mother{ protected: int x, y; public: void set(int a, int b); private: int z; } class son : private mother{ private: double b; public: void foo ( ); } void son :: foo ( ){ x = y = 20; set(5, 10); cout<<“value of b ”<<b<<endl; z = 100; // error, not a public member } son can also access 3 of the 4 inherited members CPS235:Inheritance 82
  83. 83. Class Derivation Example mother daughter granddaughter son grandson class mother{ protected: int x, y; public: void set(int a, int b); private: int z; }; CPS235:Inheritance class daughter : public mother{ private: double a; public: void foo ( ); }; class granddaughter : public daughter{ public: void foo ( ); }; 83
  84. 84. Class Derivation Example void granddaughter :: foo ( ){ x = y = 20; //OK set(5, 10); //OK cout<<“value of a ”<<a<<endl; //error: private member of daughter z = 100; // error, a private member of mother }; CPS235:Inheritance 84
  85. 85. Class Derivation Example mother daughter granddaughter son grandson class mother{ protected: int x, y; public: void set(int a, int b); private: int z; }; CPS235:Inheritance class son : private mother{ private: double b; public: void foo ( ); }; class grandson : public son{ public: void foo ( ); }; 85
  86. 86. Class Derivation Example void grandson:: foo ( ){ x = y = 20; //ERROR: not accessible set(5, 10); //ERROR: not accessible z = 100; mother // error, a private member of }; CPS235:Inheritance 86
  87. 87. Encapsulation class Figure { protected: int x, y; }; class Circle : public Figure { public: int radius; }; int main() { Circle a; a.x = 0; a.y = 0; a.radius = 10; }
  88. 88. Encapsulation class Figure { protected: int x_, y_; }; class Circle : public Figure { private: int radius_; public: Circle(int x, int y, int radius); }; Circle::Circle(int x, int y, int radius) { x_ = x; y_ = y; radius_ = radius; } int main() { Circle a(0,0,10); }
  89. 89. Encapsulation class Figure { private: int x_, y_; }; class Circle : public Figure { private: int radius_; public: Circle(int x, int y, int radius); }; Circle::Circle(int x, int y, int radius) { x_ = x; y_ = y; radius_ = radius; } int main() { Circle a(0,0,10); }
  90. 90. Encapsulation class Figure { private: int x_, y_; public: void SetX(int x); void SetY(int y); }; void Figure::SetX(int x) { x_ = x; } void Figure::SetY(int y) { y_ = y; } class Circle : public Figure { private: int radius_; public: Circle(int x, int y, int radius); }; Circle::Circle(int x, int y, int radius) { SetX(x); SetY(y); radius_ = radius; } int main() { Circle a(0,0,10); }
  91. 91. 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 – Overloaded Assignment operator – Friends Since all these functions are classspecific! CPS235:Inheritance 91
  92. 92. 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 ( ) {cout<<“A:default”<<endl; } A (int a) {cout<<“A:parameter”<<end l;} }; }; output: B test(1); CPS235:Inheritance class B : public A { public: B (int a) 92 {cout<<“B”<<endl; } A:default B
  93. 93. Constructor Rules for Derived Classes • You can also specify a constructor of the base class other than the default constructor DerivedClassCon ( derivedClass args ) : BaseClassCon ( baseClass args ) { DerivedClass constructor body } class A { class B : public A public: { A ( ) public: {cout<<“A:default”<<endl; B (int } a):A(a) A (int a) {cout<<“A:parameter”<<end l;} }; CPS235:Inheritance B test(1); }; output: 93 {cout<<“B”<<endl; } A:parameter B
  94. 94. What is the result? class Figure { public: Figure() { cout << "Figure Constructorn"; } ~Figure() { cout << "Figure Destructorn"; } }; CPS235:Inheritance class Circle : public Figure { public: Circle() { cout << "Circle Constructorn"; } ~Circle() { cout << "Circle Destructorn"; } }; int main() { Circle a; } 94
  95. 95. Constructor Rules for Derived Classes • Base constructor is called before the derived class constructor • Destructors vice versa CPS235:Inheritance 95
  96. 96. Calling the Base Class constructor class Figure { public: Figure() { cout << "Figure Constructorn"; } ~Figure() { cout << "Figure Destructorn"; } }; class Circle : public Figure { public: Circle() : Figure() { cout << "Circle Constructorn"; } ~Circle() { cout << "Circle Destructorn"; } }; int main() { Circle a; }
  97. 97. Calling the Base Class constructor class Figure { private: int x, y; public: Figure(int xVal, int yVal):x(xVal), y(yVal) { cout << "Figure Constructorn"; } ~Figure() { cout << "Figure Destructorn"; } }; class Circle : public Figure { private: double radius; public: Circle(int xVal, int yVal, int r) : Figure(xVal, yVal), radius(r) { cout << "Circle Constructorn"; } ~Circle() { cout << "Circle Destructorn"; } }; int main() { Circle a(0,0,5); }
  98. 98. Define its Own Members The derived class can also define its own members, in addition to the members inherited from the base class Point x y x y Circle r class Circle : public Point{ private: double r; public: void set_r(double c); }; CPS235:Inheritance 98 class Point{ protected: int x, y; public: void set(int a, int b); }; protected: int x, y; private: double r; public: void set(int a, int b); void set_r(double c);
  99. 99. 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 { class B : public A protected: { int x, y; public: public: void print () void print () {cout<<“FromB”<<endl; {cout<<“From } A”<<endl;} }; }; CPS235:Inheritance 99
  100. 100. Access a Method class Point { protected: int x, y; public: void set(int a, int b) {x=a; y=b;} void foo (); void print(); }; Point A; A.set(30,50); // from base class Point A.print(); // from base class Point CPS235:Inheritance 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 100
  101. 101. Putting It All Together Time Public ExtTime CPS235:Inheritance • 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 101
  102. 102. Time class example CPS235:Inheritance 102
  103. 103. class Time class Time { public: Time () :hrs(0),mins(0),secs(0){} Time (int h, int m, int s):hrs(h),mins(m),secs(s){} void Set ( int h, int m, int s ) {hrs =h;mins=m;secs=s;} void Increment ( ) {cout<<"Calling base class Increment"<<endl;} void Write ( ) const {cout<<hrs<<":"<<mins<<":"<<secs;} protected : int hrs ; int mins ; int secs ; } ; CPS235:Inheritance 103
  104. 104. Class Interface Diagram Time class Set Increment Protected data: hrs Write Time mins secs Time CPS235:Inheritance 104
  105. 105. Derived Class ExtTime 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 h, int m, int s,ZoneType z) ; ExtTime(); // default constructor private : ZoneType } ; CPS235:Inheritance zone ; // 105 added data member
  106. 106. Class Interface Diagram ExtTime class Set Increment Set Increment Protected data: hrs Write Write mins ExtTime ExtTime Time Time Private data: zone CPS235:Inheritance 106 secs
  107. 107. Implementation of ExtTime Default Constructor ExtTime :: ExtTime () { zone = EST ; } 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 CPS235:Inheritance ExtTime et1; 107
  108. 108. Implementation of ExtTime Another Constructor ExtTime :: ExtTime (int h, int m, int s, ZoneType z): Time (h, m, s),zone(z) {} ExtTime et2 (8,30,0,EST); et2 hrs = 8 mins = 30 secs = 0 zone = EST CPS235:Inheritance 108
  109. 109. Derived Class ExtTime ExtTime :: ExtTime ():zone(EST){} ExtTime :: ExtTime (int h, int m, int s, ZoneType z) : Time (h, m, s),zone(z) {} void ExtTime :: Set(int h,int m,int s, ZoneType z) { Time :: Set (h, m, s); // calling same name function of the base class zone = z; } void ExtTime ::Write()const // function overriding { string zoneString[8] = {"EST", "CST", "MST", "PST", "EDT", "CDT", "MDT", "PDT"} ; } Time :: Write ( ) ; // calling same name function of the base class cout <<' '<<zoneString[zone]<<endl; CPS235:Inheritance 109
  110. 110. Using class ExtTime int main() { ExtTime ExtTime thisTime ( 8, 35, 0, PST ) ; thatTime ; thatTime.Write( ); // prints 00:00:00 EST thatTime.Set (16, 49, 23, CDT) ; thatTime.Write( ) ; // prints 16:49:23 CDT thisTime.Increment ( ) ; //prints Calling Base Class Increment thisTime.Increment ( ) ; //prints Calling Base Class Increment thisTime.Write ( ) ; getch(); } CPS235:Inheritance // prints 08:35:02 PST 110
  111. 111. Multiple Inheritance #include <iostream> class CPolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b;} }; class COutput { public: void output (int i); }; void COutput::output (int i) { cout << i << endl; } CPS235:Inheritance 111
  112. 112. Multiple Inheritance class CRectangle: public CPolygon, public COutput { public: int area () { return (width * height); } }; class CTriangle: public CPolygon, public COutput { public: int area () { return (width * height / 2); } }; int main () { CRectangle rect; CTriangle trgl; rect.set_values (4,5); trgl.set_values (4,5); rect.output (rect.area()); trgl.output (trgl.area()); return 0; CPS235:Inheritance 112 }
  113. 113. Ambiguities in Multiple Inheritance • See code examples CPS235:Inheritance 113
  114. 114. Friend functions • A friend function of a class is defined outside that class's scope, yet has the right to access the non-public (and public) members of the class • Let‟s say you want a function to operate on objects of two different classes and access their private data, you would need to use a friend function CPS235:Inheritance 114
  115. 115. Example of friend functions class beta; //req for frifunc declaration class alpha { private: int data; public: A class cannot be referred alpha():data(3) {} friend int frifunc(alpha, beta); //friend func to until it has been declaration declared }; class beta { private: int data; public: beta():data(7) {} friend int frifunc(alpha,beta); }; CPS235:Inheritance 115 //friend func declaration
  116. 116. Example of friend functions int frifunc(alpha a, beta b) { return (a.data + b.data); } void main() { alpha aa; beta bb; cout<<frifunc(aa,bb)<<endl; getch(); } CPS235:Inheritance 116 //friend func defined //friend func called
  117. 117. friend classes • The member functions of a class can all be made friends at the same time when you make the entire class a friend • If class alpha declares class beta as a friend class, then all member functions of class beta can access private data of class alpha • It is also possible to declare only one member function of another class to be a friend CPS235:Inheritance 117
  118. 118. friend classes class beta; class alpha { private: int data; public: alpha():data(3) {} friend class beta; //friend class declaration }; class beta { public: void func(alpha a) { cout<<"alpha's data: "<<a.data; } }; CPS235:Inheritance 118
  119. 119. friend classes void main() { alpha aa; beta bb; bb.func(aa); getch(); } CPS235:Inheritance 119
  120. 120. Class member functions as friends class CSquare; class CRectangle { int width, height; public: int area () {return (width * height);} void convert (CSquare a); }; class CSquare { private: int side; public: void set_side (int a) {side=a;} friend void CRectangle::convert(CSquare); }; CPS235:Inheritance 120
  121. 121. Class member functions as friends void CRectangle::convert (CSquare a) { width = a.side; height = a.side; } int main () { CSquare sqr; CRectangle rect; sqr.set_side(4); rect.convert(sqr); cout << rect.area(); getch(); return 0; } CPS235:Inheritance 121
  122. 122. Summary (friends) • Even though the prototypes for friend functions appear in the class definition, friends are not member functions • Friend declarations can be placed anywhere in a class definition either in public, private or protected sections • Violates the data hiding principle of classes, so it should be avoided as much as possible • Friendship is granted, not taken i.e., for class B to be a friend of class A, class A must explicitly declare that class B is its friend • The friendship relation is neither symmetric nor transitive CPS235:Inheritance 122
  123. 123. Exercise • Consider a publishing company that markets both book and audiocassette versions of its work • Create a class “publication” that stores the title (a string) and price (type float) of a publication • Create a class sales that holds an array of three floats so that it can record the sales of a particular publication for the last three months • Derive two classes: “book”, which adds a page count (type int); and “tape”, which adds a playing time in minutes(type float) from both publication and sales. Each of these four classes should have a getdata() function to get its data from the user and putdata() function to display its data • An object of class book or tape should input and output publication as well as sales data along with its own data • Write a main() function to create a book object and a tape object and CPS235:Inheritance 123 exercise their input/output capabilities
  124. 124. Compulsory Reading • Deitel and Deitel (5th edition) – Topic: 10.3. Composition: Objects as Members of Classes – Topic: 10.4. Friend functions and Friend classes • Robert Lafore – Chapter 9: Inheritance (complete) – Chapter 11: Topic: Friend functions (starts on page 572 in the e-book) CPS235:Inheritance 124

×