Anda di halaman 1dari 33

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.

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 .

Example

Bicycle is a generalization of Mountain Bike. Mountain Bike is a specialization of Bicycle.

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

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.

Example
Now lets 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(); };

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.

Example
If we didnt 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.

Access Control
Access Specifier and their scope
Base Class Access Mode Private derivation Public Private Protected Private Not inherited private Derived Class Access Modes Public derivation Public Not inherited Protected Access Directly to Function Type Class Member Derived Class Member Friend Friend Class Member Private Yes No Yes Yes Public Yes Yes Yes Yes Protected Yes Yes Yes Yes Protected derivation Protected Not inherited Protected

Access control to class members

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
private : int a1;

Class B
private : int b1;

Class B: Public A
private : int b1;

protected : int a2;

protected : int b2;

protected: int a2; int b2 public: int b3;int a3;

public : int a3;

public : int b3;

Example
class Rectangle { private: float length ; // This can't be inherited public: float breadth ; // The data and member functions are inheritable void 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't inherit 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 D void main(void) { Rectangle1 r1 ; r1.Enter_lb( ); r1.Rec_area( ); r1.Display( ); }

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
private : int a1; protected : int a2; public : int a3;

Class B
private : int b1; protected : int b2; public : int b3;

Class B : private A
private : int b1; int a2,a3; protected: int b2; public: int b3;

Example
class 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(); }

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
private : int a1; protected : int a2; public : int a3;

Class B
private : int b1; protected : int b2; public : int b3;

Class B : Protected A
private : int b1; protected: int a2; int b2,a3; public: int b3;

Example
class 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 ( ); };

Example
private section a readdata ( ) public section b writedata ( ) protected section c checkvalue ( ) y putdata ( ) z check ( )

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

Simple Or Single Inheritance


Simple Or Single Inheritance is a process in which a sub class is derived from only one superclass A class Car is derived from the class Vehicle superclass(base class)

subclass(derived class)

Defining the simple Inheritance


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

Example-Payroll System Using Single Inheritance


class 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 "; } };

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:1 Enter the employee No: 150 Enter the employee Name: ram Enter the designation: Manager Enter the basic pay: 5000 Enter the HR allowance: 1000 Enter the Dearness allowance: 500 Enter the profitability Fund: 300 E.No E.name des BP HRA DA PF NP 150 ram Manager 5000 1000 500 3 00 6200

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.

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

Multiple Inheritance
Deriving a class from more than one direct base class is called multiple inheritance.
Defining the Multiple Inheritance class A { /* ... */ }; class B { /* ... */ }; class C { /* ... */ }; class X :visibilty-mode A, visibilty-mode B, visibilty-mode C { /* ... */ };

Example
class 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) ; } };

Example
void 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( ); }

Hierarchical Inheritance
If a number of classes are derived from a single base class, it is called as hierarchical inheritance
Defining the Hierarchical Inheritance Class student {.}; Class arts: visibility-mode student {....}; Class science: visibility-mode student {....}; Class commerce: visibility-mode student {.};

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

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( ); }

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

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 inheritance Exceptions and Inheritance Overload resolution and inheritance

Disadvantage

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.

Anda mungkin juga menyukai