inheritance

33
INHERITANCE

Upload: techmx

Post on 27-Oct-2014

50 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Inheritance

INHERITANCE

Page 2: Inheritance

Introduction

• Inheritance in C++ is one of the major aspects of Object Oriented Programming (OOP). It is the process by which one object can inherit or acquire the features of another object.

• Inheritance is the process by which new classes called derived classes are created from existing classes called base classes.

Page 3: Inheritance

Introduction

• It is a way of creating new class(derived class) from the existing class(base class) providing the concept of reusability.

• The class being refined is called the superclass or base class and each refined version is called a subclass or derived class.

• Semantically, inheritance denotes an “is-a” relationship between a class and one or more refined version of it.

• Attributes and operations common to a group of subclasses are attached to the superclass and shared by each subclass providing the mechanism for class level Reusability .

Page 4: Inheritance

Example

Base class

Derived Classes

“Bicycle” is a generalization of “Mountain Bike”.

“Mountain Bike” is a specialization of

“Bicycle”.

Page 5: Inheritance

Defining a Base Class

• Base class has general features common to all the derived classes and derived class (apart from having all the features of the base class) adds specific features. This enables us to form a hierarchy of classes.

class Base-class{

... ... ... ………….//Members of base

class};

Page 6: Inheritance

Defining a Derived Class• The general form of deriving a subclass from a base class is as follows

Class derived-class-name : visibility-mode base-class-name{

……………… // ……………….// members of the derived class

};

• The visibility-mode is optional. • It may be either private or public or protected, by default it is private. • This visibility mode specifies how the features of base class are

visible to the derived class.

Page 7: Inheritance

Example• Now let’s take the example of ‘computer’ class a bit further by actually

defining it.class computer {

int speed; int main_memory; int harddisk_memory;

public: void set_speed(int);void set_mmemory(int);

void set_hmemory(int); int get_speed(); int get_mmemory(); int get_hmemory();

};

Page 8: Inheritance

Example

• As you can see, the features (properties and functions) defined in the class computer is common to laptops, desktops etc. so we make their classes inherit the base class ‘computer’.

class laptop:public computer {

int battery_time; float weight;

public: void set_battime(int); void set_weight(float); Int get_battime(); float get_weight();

};• This way the class laptop has all the features of the base class ‘computer’ and

at the same time has its specific features (battery_time, weight) which are specific to the ‘laptop’ class.

Page 9: Inheritance

Example

• If we didn’t use inheritance we would have to define the laptop class something like this:class laptop {

int speed; int main_memory; int harddisk_memory; int battery_time; float weight;

public: void set_speed(int); void set_mmemory(int); void set_hmemory(int); int get_speed(); int get_mmemory(); int get_hmemory();

void set_battime(int); void set_weight(float); int get_battime();

float get_weight(); };

• And then again we would have to do the same thing for desktops and any other class that would need to inherit from the base class ‘computer’.

Page 10: Inheritance

Access Control• Access Specifier and their scope

Access control to class members

Base Class Access Mode

Derived Class Access Modes

Private derivation

Public derivation Protected derivation

Public Private Public Protected

Private Not inherited Not inherited Not inherited

Protected private Protected Protected

Function TypeAccess Directly to

Private Public Protected

Class Member Yes Yes Yes

Derived Class Member No Yes Yes

Friend Yes Yes Yes

Friend Class Member Yes Yes Yes

Page 11: Inheritance

Public• By deriving a class as public, the public

members of the base class remains public members of the derived class and protected members remain protected members.

Class A Class B Class B: Public A

private : int a1;

protected : int a2;

public : int a3;

private : int b1;

protected : int b2;

public : int b3;

private : int b1;

protected: int a2; int b2

public:int b3;int a3;

Page 12: Inheritance

Example

class Rectangle{private:float length ; // This can't be inheritedpublic:float breadth ; // The data and member functions are inheritablevoid Enter_lb(void){cout << "\n Enter the length of the rectangle : "; cin >> length ;cout << "\n Enter the breadth of the rectangle : "; cin >> breadth ;}float Enter_l(void){ return length ; } }; // End of the class definition

class Rectangle1 : public Rectangle { private:float area ;public:void Rec_area(void)

{ area = Enter_l( ) * breadth ; } // area = length * breadth ; can't be used here

void Display(void){cout << "\n Length = " << Enter_l( ) ;

/* Object of the derived class can'tinherit the private member of the base class. Thus the member function is used here to get the value of data member 'length'.*/cout << "\n Breadth = " << breadth ;cout << "\n Area = " << area ;}}; // End of the derived class definition Dvoid main(void){Rectangle1 r1 ;r1.Enter_lb( );r1.Rec_area( );r1.Display( );}

Page 13: Inheritance

Private• If we use private access-specifier while deriving a class

then both the public and protected members of the base class are inherited as private members of the derived class and hence are only accessible to its members.

Class A Class B Class B : private A

private : int a1;

protected : int a2;

public : int a3;

private : int b1;

protected : int b2;

public : int b3;

private :int b1; int a2,a3;

protected:int b2; public:int b3;

Page 14: Inheritance

Exampleclass Rectangle

{int length, breadth;public:void enter(){cout << "\n Enter length: "; cin >> length;cout << "\n Enter breadth: "; cin >> breadth;}int getLength(){return length;}int getBreadth(){return breadth;}void display(){cout << "\n Length= " << length;cout << "\n Breadth= " << breadth;}

};

class RecArea : private Rectangle{

public:void area_rec(){enter();cout << "\n Area = " << (getLength() * getBreadth());}};void main(){clrscr();RecArea r ;r.area_rec();getch();}

Page 15: Inheritance

Protected• It makes the derived class to inherit the protected

and public members of the base class as protected members of the derived class.Class A Class B Class B : Protected A

private : int a1;

protected : int a2;

public : int a3;

private : int b1;

protected : int b2;

public : int b3;

private : int b1;

protected:int a2; int b2,a3;

public:int b3;

Page 16: Inheritance

Exampleclass student{private :int x;void getdata ( );public:int y;void putdata ( );protected:int z;void check ( );};

class marks : protected student{private :int a ;void readdata ( );public :int b;void writedata ( );protected :int c;void checkvalue ( );};

Page 17: Inheritance

Exampleprivate sectiona readdata ( )public sectionb writedata ( )protected sectionc checkvalue ( )y putdata ( )z check ( )

Page 18: Inheritance

Types of Inheritance• Inheritance are of the following types

• Simple or Single Inheritance• Multi level or Varied Inheritance• Multiple Inheritance• Hierarchical Inheritance• Hybrid Inheritance• Virtual Inheritance

Page 19: Inheritance

Simple Or Single Inheritance

superclass(base class)

subclass(derived class)

• A class Car is derived from the class Vehicle

• Simple Or Single Inheritance is a process in which a sub class is derived from only one superclass

Defining the simple Inheritance

class vehicle

{ ….. }; class car : visibility-mode vehicle{

………… };

Page 20: Inheritance

Example-Payroll System Using Single Inheritanceclass emp{ public: int eno; char name[20],des[20]; void get() { cout<<"Enter the employee number:"; cin>>eno; cout<<"Enter the employee name:"; cin>>name; cout<<"Enter the designation:"; cin>>des; }}; class salary:public emp{ float bp,hra,da,pf,np; public: void get1() {

cout<<"Enter the basic pay:"; cin>>bp; cout<<"Enter the Humen ResourceAllowance:"; cin>>hra; cout<<"Enter the Dearness Allowance :"; cin>>da; cout<<"Enter the Profitablity Fund:"; cin>>pf; } void calculate() { np=bp+hra+da-pf; } void display() { cout<<eno<<"\t"<<name<<"\t"<<des<<"\

t"<<bp<<"\t"<<hra<<"\t"<<da<<"\t"<<pf<<"\t"<<np<<"\n";

}};

Page 21: Inheritance

Example-Payroll System Using Single Inheritance

void main(){ int i,n; char ch; salary s[10]; clrscr(); cout<<"Enter the number of employee:"; cin>>n; for(i=0;i<n;i++) { s[i].get(); s[i].get1(); s[i].calculate(); } cout<<"\ne_no \t e_name\t des \t bp \thra

\t da \t pf \t np \n"; for(i=0;i<n;i++)

{s[i].display() } getch(); }Output:Enter the Number of employee:1Enter the employee No: 150Enter the employee Name: ramEnter the designation: ManagerEnter the basic pay: 5000Enter the HR allowance: 1000Enter the Dearness allowance: 500Enter the profitability Fund: 300 E.No E.name des BP HRA DA PF

NP150 ram Manager 5000 1000 500 300

6200

Page 22: Inheritance

Multi level or Varied Inheritance• It has been discussed so far that a class can be derived from a class.

• C++ also provides the facility of multilevel inheritance, according to which the derived class can also be derived by an another class, which in turn can further be inherited by another and so on called as Multilevel or varied Inheritance.

• In the above figure, class B represents the base class. The class D1 that is called first level of inheritance, inherits the class B. The derived class D1 is further inherited by the class D2, which is called second level of inheritance.

Page 23: Inheritance

Example

class Base{protected:int b;public:void EnterData( ){cout << "\n Enter the value of b: ";cin >> b;}void DisplayData( ){cout << "\n b = " << b;}};class Derive1 : public Base{protected:int d1;public:void EnterData( ){Base:: EnterData( );cout << "\n Enter the value of d1: ";cin >> d1;}void DisplayData( ){

Base::DisplayData();cout << "\n d1 = " << d1;}};class Derive2 : public Derive1{private:int d2;public:void EnterData( ){Derive1::EnterData( );cout << "\n Enter the value of d2: ";cin >> d2;}void DisplayData( ){Derive1::DisplayData( );cout << "\n d2 = " << d2;}};int main( ){Derive2 objd2;objd2.EnterData( );objd2.DisplayData( );return 0;}

Page 24: Inheritance

Multiple Inheritance

• Deriving a class from more than one direct base class is called multiple inheritance.

Defining the Multiple Inheritanceclass A { /* ... */ }; class B { /* ... */ }; class C { /* ... */ }; class X :visibilty-mode A, visibilty-mode B, visibilty-mode C { /* ... */ };

Page 25: Inheritance

Exampleclass Circle // First base class{ protected:float radius ; public:void Enter_r(void){ cout << "\n\t Enter the radius: "; cin >> radius ;}void Display_ca(void){ cout << "\t The area = " << (22/7 * radius*radius) ;}};class Rectangle // Second base class{protected:float length, breadth ;public:void Enter_lb(void){

cout << "\t Enter the length : ";

cin >> length ;cout << “\t Enter the breadth : ” ; cin >> breadth ;}void Display_ar(void){cout << "\t The area = " << (length * breadth);}};class Cylinder : public Circle, public Rectangle { public:void volume_cy(void){cout << "\t The volume of the cylinder is: "<< (22/7* radius*radius*length) ;}};

Page 26: Inheritance

Examplevoid main(void)

{Circle c ;cout << "\n Getting the radius of the circle\n" ;c.Enter_r( );c.Display_ca( );Rectangle r ;cout << "\n\n Getting the length and breadth of the rectangle\n\n";r.Enter_l( );r.Enter_b( );r.Display_ar( );Cylinder cy ; cout << "\n\n Getting the height and radius of the cylinder\n";cy.Enter_r( );cy.Enter_lb( );cy.volume_cy( );

}

Page 27: Inheritance

Hierarchical Inheritance• If a number of classes are derived from a single base class, it is called

as hierarchical inheritance

• Defining the Hierarchical InheritanceClass student{…………….};Class arts: visibility-mode student{………..…..};Class science: visibility-mode student{…………....};Class commerce: visibility-mode student{…………….};

Page 28: Inheritance

Example

const int len = 20 ;class student // BASE CLASS{private: char F_name[len] , L_name[len] ;int age, int roll_no ;public:void Enter_data(void){cout << "\n\t Enter the first name: " ; cin >> F_name ;cout << "\t Enter the second name: "; cin >> L_name ;cout << "\t Enter the age: " ; cin >> age ;cout << "\t Enter the roll_no: " ; cin >> roll_no ;}void Display_data(void){cout << "\n\t First Name = " << F_name ;cout << "\n\t Last Name = " << L_name ;cout << "\n\t Age = " << age ;cout << "\n\t Roll Number = " << roll_no ;}};

class arts : public student // FIRST DERIVED CLASS{

private: char asub1[len] ;char asub2[len] ;char asub3[len] ;public:void Enter_data(void){ student :: Enter_data( );cout << "\t Enter the subject1 of the arts student: "; cin >> asub1 ;cout << "\t Enter the subject2 of the arts student: "; cin >> asub2 ;cout << "\t Enter the subject3 of the arts student: "; cin >> asub3 ;}void Display_data(void){student :: Display_data( );cout << "\n\t Subject1 of the arts student = " << asub1 ;cout << "\n\t Subject2 of the arts student = " << asub2 ;cout << "\n\t Subject3 of the arts student = " << asub3 ;}};

Page 29: Inheritance

Example

class commerce : public student // SECOND DERIVED CLASS{private: char csub1[len], csub2[len], csub3[len] ;public: void Enter_data(void){student :: Enter_data( );cout << "\t Enter the subject1 of the commerce student: "; cin >> csub1;cout << "\t Enter the subject2 of the commercestudent:"; cin >> csub2 ;cout << "\t Enter the subject3 of the commerce student: "; cin >> csub3 ;}void Display_data(void){student :: Display_data( );cout << "\n\t Subject1 of the commerce student = " << csub1 ;cout << "\n\t Subject2 of the commerce student = " << csub2 ;cout << "\n\t Subject3 of the commerce student = " << csub3 ;}};

void main(void){arts a ;cout << "\n Entering details of the arts student\n" ;a.Enter_data( );cout << "\n Displaying the details of the arts student\n" ;a.Display_data( );science s ;cout << "\n\n Entering details of the science student\n" ;s.Enter_data( );cout << "\n Displaying the details of the science student\n" ;s.Display_data( );commerce c ;cout << "\n\n Entering details of the commerce student\n" ;c.Enter_data( );cout << "\n Displaying the details of the commerce student\n";c.Display_data( );}

Page 30: Inheritance

Hybrid Inheritance• In this type, more than one type of inheritance are used to

derive a new sub class.• Multiple and multilevel type of inheritances are used to

derive a class PG-Student. class Person

{ ……};class Student : public Person { ……};class Gate Score

{…….};class PG - Student : public Student,

public Gate Score{………};

Person

Student

PG - Student

Gate Score

Page 31: Inheritance

Features or Advantages of Inheritance:

Reusability: • Inheritance helps the code to be reused in many situations. The base

class is defined and once it is compiled, it need not be reworked. Using the concept of inheritance, the programmer can create as many derived classes from the base class as needed while adding specific features to each derived class as needed.

Saves Time and Effort: • The above concept of reusability achieved by inheritance saves the

programmer time and effort. Since the main code written can be reused in various situations as needed

Runtime type inheritanceExceptions and InheritanceOverload resolution and inheritance

Page 32: Inheritance

Disadvantage

Page 33: Inheritance

Conclusion

• In general, it's a good idea to prefer less inheritance. Use inheritance only in the specific situations in which it's needed. Large inheritance hierarchies in general, and deep ones in particular, are confusing to understand and therefore difficult to maintain. Inheritance is a design-time decision and trades off a lot of runtime flexibility.