+ All Categories
Home > Documents > Inheritance

Inheritance

Date post: 09-Feb-2016
Category:
Upload: portia
View: 16 times
Download: 0 times
Share this document with a friend
Description:
LEARN. Inheritance. BY EXAMPLES. Saras M. Srivastava PGT – Comp. Sc. Kendriya Vidyalaya Air Force Station Makarpura , Vadodara - 390014. Example1. class PUBLISHER { char pub[12]; double turnover; protected: void register( ); public: PUBLISHER( ); void enter( ); - PowerPoint PPT Presentation
Popular Tags:
49
BY EXAMPLES Inheritan ce Saras M. Srivastava PGT – Comp. Sc. Kendriya Vidyalaya Air Force Station Makarpura, Vadodara - 390014 LEARN 1
Transcript
Page 1: Inheritance

1

BY EXAMPLES

Inheritance

Saras M. Srivastava

PGT – Comp. Sc.Kendriya Vidyalaya

Air Force Station Makarpura,Vadodara - 390014

LEARN

Page 2: Inheritance

2

class PUBLISHER {

char pub[12];double turnover;protected:void register( );public:PUBLISHER( );void enter( );void display( );

};

Example1

Page 3: Inheritance

3

class BRANCH {

char city[20];protected:

float employees; public:

BRANCH( );void haveit( );void giveit( );

};

Page 4: Inheritance

4

class AUTHOR: private BRANCH, public PUBLISHER

{int acode;char aname[20];float amount;

public:AUTHOR( );void start( );void show( );

};

Page 5: Inheritance

5

Write the names of data members. Which are accessible from objects belonging to class AUTHOR.

Write the names of all the member functions which are accessible from objects belonging to class BRANCH.

Write the names of all the members which are accessible from member functions of class AUTHOR.

How many bytes will be required by an object belonging to class AUTHOR?

Questions

Page 6: Inheritance

6

class Mydata { protected:

int data;public:

void Get_mydata(int);void Manip_mydata(int);void Show_mydata(int);Mydata( );~Mydata( );

};

Example 2

Page 7: Inheritance

7

class Personal_data{protected:

int data1;public:

void Get_personaldata(int);void Show_personaldata(int);Personal_data( );~Personal_data( );

};

Page 8: Inheritance

8

class Person: public Mydata, Personal_data{

public:void Show_person(void);Person( );~Person( );

};

Page 9: Inheritance

9

i) How many bytes will be required by an object belonging to class Person?

ii) Which type of inheritance is depicted in the above example?

iii) List the data members that can be accessed by the member function Show_person( ).

iv) What is the order of constructor execution at the time of creating an object of class Person?

Questions

Page 10: Inheritance

10

class Goods { int id;protected :char name[20];long qty;void Incr(int n);public :Goods();~Goods();void get(); };

Example 3

Page 11: Inheritance

11

class Food_products : public Goods{

char exp_dt[10];protected :

int id;int qty;

public :void getd();void showd();

};

Page 12: Inheritance

12

class Cosmetics : private Goods{

int qty;char exp_date[10];

protected :int id;

public :~Cosmetics();Cosmetics();void show();

};

Page 13: Inheritance

13

(i) How many bytes will be required by an object of class Food_products.

(ii) Name the member functions accessible through the object of class Food_products.

(iii) From the following, Identify the member function(s) that cannot be called directly from the object of class Cosmeticsshow(), getd(), get()

(iv) If the class cosmetics inherits the properties of food_products class also, then name the type of inheritance.

Questions

Page 14: Inheritance

14

class livingbeing{

char specification[20];int averageage;

public:void read();void show();

};

Example 4

Page 15: Inheritance

15

class ape : private livingbeing{ int no_of_organs, no_of_bones; protected:

int iq_level; public:

void readape();void showape();

};

Page 16: Inheritance

16

class human : public ape{

char race[20];char habitation[30];

public:void readhuman();void showhuman();

};

Page 17: Inheritance

17

a. Name the members which can be accessed from the member functions of class human.

b. Name the members, which can be accessed by an object of class human.

c. What will be the size of an object (in bytes) of class human.

d. Name the class(es) that can access read() declared in livingbeing class.

Questions

Page 18: Inheritance

18

class vehicle{ int wheels;

protected:int passenger;

public:void inputdata();void outputdata();

};

Example 5

Page 19: Inheritance

19

class heavyvehicle : protected vehicle{ int diesel_petrol;

protected:int load;public:void readdata(int, int);void writedata();

};

Page 20: Inheritance

20

class bus : private heavyvehicle{ char make[20];

public:void fetchdata();void displaydata();

};

Page 21: Inheritance

21

Name the base class and derived class of heavyvehicle class.

Name the data member(s) that can be accessed from the function displaydata().

How many bytes will be required by an object of vehicle and heavyvehicle classes respectively?

Is the member function outputdata() accessible to the objects of the class heavyvehicle?

Questions

Page 22: Inheritance

22

RectangleTriangle

Polygon

class Polygon{protected: int numVertices; float *xCoord, float *yCoord;public: void set(float *x, float *y, int nV);

};

class Rectangle : public Polygon{public: float area();

};

class Rectangle{protected: int numVertices; float *xCoord, float *yCoord;public: void set(float *x, float *y, int nV); float area();

};

Inheritance Concept

Page 23: Inheritance

23

RectangleTriangle

Polygon

class Polygon{protected: int numVertices; float *xCoord, float *yCoord;public: void set(float *x, float *y, int nV);

};

class Triangle : public Polygon{public: float area();

};

class Triangle{protected: int numVertices; float *xCoord, float *yCoord;public: void set(float *x, float *y, int nV); float area();

};

Inheritance Concept

Page 24: Inheritance

24

Inheritance ConceptPoint

Circle 3D-Point

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

};

class Circle : public Point{private:

double r;};

class 3D-Point: public Point{private:

int z;};

xy

xyr

xyz

Page 25: Inheritance

25

Augmenting the original class

Specializing the original class

Inheritance Concept

RealNumber

ComplexNumber

ImaginaryNumber

Rectangle Triangle

Polygon Point

Circle 3D-Point

Page 26: Inheritance

26

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

Page 27: Inheritance

27

Define a Class Hierarchy

Syntax:class DerivedClassName : access-level BaseClassName

where access-level specifies the type of derivation

private by default, orpublic

Any class can serve as a base classThus a derived class can also be a base class

Page 28: Inheritance

28

Class DerivationPoint

3D-Point

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

};

class 3D-Point : public Point{private:

double z;… …

};

class Sphere : public 3D-Point{private:

double r;… …

};

Sphere

Point is the base class of 3D-Point, while 3D-Point is the base class of Sphere

Page 29: Inheritance

29

What to inherit?

In principle, every member of a base class is inherited by a derived class just with different access permission

Page 30: Inheritance

30

Access Control Over the MembersTwo levels of access

control over class membersclass definitioninheritance type

base c lass / superc lass /pa ren t c lass

de riv ed c lass / subc lass /ch ild c lass

deriv

e fro

m

mem

bers

goe

s to

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

};class Circle : public Point{

… …};

Page 31: Inheritance

31

The type of inheritance defines the access level for the members of derived class that are inherited from the base class

Access Rights of Derived Classes

private protected publicprivate - - -protected private protected protectedpublic private protected public

Type of Inheritance

Access C

ontrolfor M

embers

Page 32: Inheritance

32

class daughter : --------- mother{private: double dPriv;public: void mFoo ( );

};

Class Derivationclass mother{

protected: int mProc;public: int mPubl;private: int mPriv;

};

class daughter : --------- mother{private: double dPriv;public: void dFoo ( );

};void daughter :: dFoo ( ){

mPriv = 10; //errormProc = 20;

};

private/protected/public int main() {

/*….*/}

class grandDaughter : public daughter {private: double gPriv;public: void gFoo ( );

};

Page 33: Inheritance

33

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 forconstructor and destructor friendsSince all these functions are class-specific

Page 34: Inheritance

34

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”<<endl;}

};

class B : public A { public:

B (int a) {cout<<“B”<<endl;}

};

B test(1);A:defaultB

output:

Page 35: Inheritance

35

Constructor Rules for Derived Classes You can also specify an constructor of the base class other than the default constructor

class A { public:

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

};

class C : public A { public:

C (int a) : A(a) {cout<<“C”<<endl;}

};

C test(1);A:parameterC

output:

DerivedClassCon ( derivedClass args ) : BaseClassCon ( baseClass args )

{ DerivedClass constructor body }

Page 36: Inheritance

36

Define its Own Members

Point

Circle

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

};

class Circle : public Point{private:

double r;public:

void set_r(double c);

};

xy

xyr

class Circle{ protected:

int x, y;private: double r;public: void set(int a, int b); void set_r(double c);

};

The derived class can also define its own members, in addition to the members inherited from the base class

Page 37: Inheritance

37

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 (){cout<<“From

A”<<endl;}};

class B : public A { public:

void print () {cout<<“From B”<<endl;}

};

Page 38: Inheritance

38

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

{x=a; y=b;} 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(); };

Access a Method

Circle C;C.set(10,10,100); // from class CircleC.foo (); // from base class PointC.print(); // from class Circle

Point A;A.set(30,50); // from base

class PointA.print(); // from base class

Point

Page 39: Inheritance

39

Putting Them TogetherTime is the base classExtTime is the derived class

with public inheritanceThe 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

ExtTime

Time

Page 40: Inheritance

40

class Time Specificationclass 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 ;

} ;

// SPECIFICATION FILE ( time.h)

Page 41: Inheritance

41

Class Interface Diagram

Protected data:hrs

mins

secs

Set

Increment

Write

Time

Time

Time class

Page 42: Inheritance

42

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

} ;

Page 43: Inheritance

43

Class Interface Diagram

Protected data:hrs

mins

secs

ExtTime class

Set

Increment

Write

Time

Time

Set

Increment

Write

ExtTime

ExtTime

Private data:zone

Page 44: Inheritance

44

Implementation of ExtTime

Default Constructor

ExtTime :: ExtTime ( )

{ zone = EST ;

}The default constructor of base class, Time(), is automatically called, when an ExtTime object is created.

ExtTime et1;

hrs = 0mins = 0secs = 0zone = EST

et1

Page 45: Inheritance

45

Implementation of ExtTimeAnother 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); hrs = 8

mins = 30secs = 0zone = EST

et2

5000

???6000

5000

Page 46: Inheritance

46

Implementation of ExtTimevoid 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;}

Page 47: Inheritance

47

Working with ExtTime #include “exttime.h”

… …int main()

{ ExtTime thisTime ( 8, 35, 0, PST ) ; ExtTime thatTime ; // default constructor calledthatTime.Write( ) ; // outputs 00:00:00 ESTthatTime.Set (16, 49, 23, CDT) ; thatTime.Write( ) ; // outputs 16:49:23 CDTthisTime.Increment ( ) ;thisTime.Increment ( ) ;thisTime.Write ( ) ; // outputs 08:35:02 PST}

Page 48: Inheritance

48

Take Home MessageInheritance 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

Page 49: Inheritance

49

QUESTIONS


Recommended