Inheritance

1,523 views

Published on

Published in: Technology, Sports
  • Be the first to comment

Inheritance

  1. 1. INHERITANCE
  2. 2. 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.
  3. 3. 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 .
  4. 4. Example “Bicycle” is a generalization of “Mountain Bike”. “Mountain Bike” is a specialization of “Bicycle”.
  5. 5. 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 };
  6. 6. 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.
  7. 7. 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(); };
  8. 8. 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.
  9. 9. 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’.
  10. 10. Access Control • Access Specifier and their scopeBase Class Access Derived Class Access Modes Mode Private Public derivation Protected derivation derivationPublic Private Public ProtectedPrivate Not inherited Not inherited Not inheritedProtected private Protected Protected Access Directly to Function Type Private Public Protected Access Class Member Yes Yes Yes control to Derived Class Member No Yes Yes class Friend Yes Yes Yes members Friend Class Member Yes Yes Yes
  11. 11. 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 : private : private : int a1; int b1; int b1; protected : protected : protected: int a2; int b2; int a2; int b2 public : public : public: int a3; int b3; int b3;int a3;
  12. 12. Exampleclass Rectangle void Rec_area(void) { { area = Enter_l( ) * breadth ; } private: // area = length * breadth ; cant be used float length ; // This cant be inherited here public: float breadth ; // The data and member void Display(void) functions are inheritable { void Enter_lb(void) cout << "n Length = " << Enter_l( ) ; { /* Object of the derived class cant cout << "n Enter the length of the inherit the private member of the base rectangle : "; class. Thus the member cin >> length ; function is used here to get the value of cout << "n Enter the breadth of the data member length.*/ rectangle : "; cout << "n Breadth = " << breadth ; cin >> breadth ; cout << "n Area = " << area ; } } float Enter_l(void) }; // End of the derived class definition D { return length ; } void main(void) }; // End of the class definition { Rectangle1 r1 ; class Rectangle1 : public Rectangle r1.Enter_lb( ); { r1.Rec_area( ); private: r1.Display( ); float area ; } public:
  13. 13. 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 : private : private : int a1; int b1; int b1; int a2,a3; protected : protected : int a2; int b2; protected: int b2; public : public : int a3; int b3; public: int b3;
  14. 14. Exampleclass Rectangle } { }; int length, breadth; public: class RecArea : private Rectangle void enter() { { cout << "n Enter length: "; cin >> public: length; void area_rec() cout << "n Enter breadth: "; cin >> { breadth; enter(); } cout << "n Area = " << (getLength() * int getLength() getBreadth()); { } return length; }; } void main() int getBreadth() { { clrscr(); return breadth; RecArea r ; } r.area_rec(); void display() getch(); { } cout << "n Length= " << length; cout << "n Breadth= " << breadth;
  15. 15. 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 : private : private : int a1; int b1; int b1; protected : protected : protected: int a2; int b2; int a2; int b2,a3; public : public : public: int a3; int b3; int b3;
  16. 16. Exampleclass student {{ private :private : int a ;int x; void readdata ( );void getdata ( ); public :public: int b;int y; void writedata ( );void putdata ( ); protected :protected: int c;int z; void checkvalue ( );void check ( ); };};class marks : protected student
  17. 17. Exampleprivate sectiona readdata ( )public sectionb writedata ( )protected sectionc checkvalue ( )y putdata ( )z check ( )
  18. 18. 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
  19. 19. Simple Or Single Inheritance • Simple Or Single Inheritance is a process in which a sub class is derived superclass(base class) from only one superclass • A class Car is derived from the class Vehicle subclass(derived class)Defining the simple Inheritance class vehicle { ….. }; class car : visibility-mode vehicle { ………… };
  20. 20. Example-Payroll System Using Single Inheritanceclass emp {{ cout<<"Enter the basic pay:"; public: cin>>bp; int eno; cout<<"Enter the Humen ResourceAllowance:"; char name[20],des[20]; cin>>hra; void get() cout<<"Enter the Dearness Allowance :"; { cin>>da; cout<<"Enter the employee number:"; cout<<"Enter the Profitablity Fund:"; cin>>eno; cin>>pf; cout<<"Enter the employee name:"; } cin>>name; void calculate() cout<<"Enter the designation:"; { cin>>des; np=bp+hra+da-pf; } }}; void display() { cout<<eno<<"t"<<name<<"t"<<des<<"t"<<bp<class salary:public emp <"t"<<hra<<"t"<<da<<"t"<<pf<<"t"<<np<<"n{ "; float bp,hra,da,pf,np; } public: }; void get1()
  21. 21. Example-Payroll System Using Single Inheritancevoid main() {s[i].display() }{ getch(); } int i,n; Output: char ch; Enter the Number of employee:1 salary s[10]; Enter the employee No: 150 clrscr(); Enter the employee Name: ram cout<<"Enter the number of Enter the designation: Manager employee:"; Enter the basic pay: 5000 cin>>n; Enter the HR allowance: 1000 for(i=0;i<n;i++) Enter the Dearness allowance: 500 { Enter the profitability Fund: 300 s[i].get(); s[i].get1(); E.No E.name des BP HRA DA PF s[i].calculate(); NP } 150 ram Manager 5000 1000 500 3 cout<<"ne_no t e_namet des t bp 00 6200 thra t da t pf t np n"; for(i=0;i<n;i++)
  22. 22. 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.
  23. 23. Exampleclass Base cout << "n d1 = " << d1; { } protected: }; int b; class Derive2 : public Derive1 public: { void EnterData( ) private: { int d2; cout << "n Enter the value of b: "; public: cin >> b; void EnterData( ) } { void DisplayData( ) Derive1::EnterData( ); { cout << "n Enter the value of d2: "; cout << "n b = " << b; cin >> d2; } } }; void DisplayData( ) class Derive1 : public Base { { Derive1::DisplayData( ); protected: cout << "n d2 = " << d2; int d1; } public: }; void EnterData( ) int main( ) { { Base:: EnterData( ); Derive2 objd2; cout << "n Enter the value of d1: "; objd2.EnterData( ); cin >> d1; objd2.DisplayData( ); } return 0; void DisplayData( ) } { Base::DisplayData();
  24. 24. 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{ /* ... */ };
  25. 25. Exampleclass Circle // First base class{protected: cin >> length ;float radius ; cout << “t Enter the breadth : ” ;public: cin >> breadth ;void Enter_r(void){ }cout << "nt Enter the radius: "; void Display_ar(void) {cin >> radius ; cout << "t The area = " << (length *} breadth);void Display_ca(void) }{ };cout << "t The area = " << (22/7 * class Cylinder : public Circle, publicradius*radius) ; Rectangle} {}; public:class Rectangle // Second base class void volume_cy(void){ {protected: cout << "t The volume of the cylinder is: "float length, breadth ; << (22/7* radius*radius*length) ;public: }void Enter_lb(void) };{cout << "t Enter the length : ";
  26. 26. Examplevoid main(void) { Circle c ; cout << "n Getting the radius of the circlen" ; c.Enter_r( ); c.Display_ca( ); Rectangle r ; cout << "nn Getting the length and breadth of the rectanglenn"; r.Enter_l( ); r.Enter_b( ); r.Display_ar( ); Cylinder cy ; cout << "nn Getting the height and radius of the cylindern"; cy.Enter_r( ); cy.Enter_lb( ); cy.volume_cy( ); }
  27. 27. 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{…………….};
  28. 28. Example {const int len = 20 ;class student // BASE CLASS private:{ char asub1[len] ;private: char F_name[len] , L_name[len] ; char asub2[len] ;int age, int roll_no ; char asub3[len] ;public: public:void Enter_data(void) void Enter_data(void){ { student :: Enter_data( );cout << "nt Enter the first name: " ; cin >> cout << "t Enter the subject1 of the artsF_name ; student: "; cin >> asub1 ;cout << "t Enter the second name: "; cin >> cout << "t Enter the subject2 of the artsL_name ; student: "; cin >> asub2 ;cout << "t Enter the age: " ; cin >> age ; cout << "t Enter the subject3 of the artscout << "t Enter the roll_no: " ; cin >> roll_no student: "; cin >> asub3 ;}; void Display_data(void)} {student :: Display_data( );void Display_data(void) cout << "nt Subject1 of the arts student = "{ << asub1 ;cout << "nt First Name = " << F_name ; cout << "nt Subject2 of the arts student = "cout << "nt Last Name = " << L_name ; << asub2 ;cout << "nt Age = " << age ; cout << "nt Subject3 of the arts student = "cout << "nt Roll Number = " << roll_no ; << asub3 ;}}; }};class arts : public student // FIRST DERIVEDCLASS
  29. 29. Exampleclass commerce : public student // SECONDDERIVED CLASS{private: char csub1[len], csub2[len], csub3[len] ;public:void Enter_data(void){ void main(void)student :: Enter_data( ); {cout << "t Enter the subject1 of the commerce arts a ;student: "; cout << "n Entering details of the arts studentn" ;cin >> csub1; a.Enter_data( );cout << "t Enter the subject2 of the cout << "n Displaying the details of the artscommercestudent:"; studentn" ;cin >> csub2 ; a.Display_data( );cout << "t Enter the subject3 of the commerce science s ;student: "; cout << "nn Entering details of the sciencecin >> csub3 ; studentn" ;} s.Enter_data( );void Display_data(void) cout << "n Displaying the details of the science{ studentn" ;student :: Display_data( ); s.Display_data( );cout << "nt Subject1 of the commerce student = " commerce c ;<< csub1 ; cout << "nn Entering details of the commercecout << "nt Subject2 of the commerce student = " studentn" ;<< csub2 ; c.Enter_data( );cout << "nt Subject3 of the commerce student = " cout << "n Displaying the details of the commerce<< csub3 ; studentn";} c.Display_data( );}; }
  30. 30. 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 { ……}; Personclass Student : public Person { ……};class Gate Score Student Gate Score {…….};class PG - Student : public Student, PG - Student public Gate Score {………};
  31. 31. 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 neededRuntime type inheritanceExceptions and InheritanceOverload resolution and inheritance
  32. 32. Disadvantage
  33. 33. Conclusion• In general, its a good idea to prefer less inheritance. Use inheritance only in the specific situations in which its 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.

×