C Inheritance Arrange concepts into an inheritance hierarchy

  • Slides: 40
Download presentation
C++ Inheritance

C++ Inheritance

Arrange concepts into an inheritance hierarchy • Concepts at higher levels are more general

Arrange concepts into an inheritance hierarchy • Concepts at higher levels are more general • Concepts at lower levels are more specific (inherit properties of concepts at higher levels) Vehicle Wheeled vehicle Car 2 -door Bicycle 4 -door Boat

C++ Inheritance One of the most important concepts in object-oriented programming is that of

C++ Inheritance One of the most important concepts in object-oriented programming is that of inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and fast implementation time. When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class.

C++ Inheritance is the process by which new classes called derived classes are created

C++ Inheritance is the process by which new classes called derived classes are created from existing classes called base classes. The derived classes have all the features of the base class and the programmer can choose to add new features specific to the newly created derived class.

The "is a" Relationship • Inheritance establishes an "is a" relationship between classes. –

The "is a" Relationship • Inheritance establishes an "is a" relationship between classes. – A poodle is a dog – A car is a vehicle – A flower is a plant – A football player is an athlete 5

C++ Inheritance Features or Advantages of Inheritance: Reusability: üInheritance helps the code to be

C++ 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.

C++ Inheritance Features or Advantages of Inheritance: üSaves Time and Effort: The above concept

C++ Inheritance Features or Advantages of Inheritance: üSaves Time and Effort: The above concept of reusability achieved by inheritance saves the programmer time and effort. The main code written can be reused in various situations as needed. üIncreases Program Structure which results in greater reliability.

Advantages of inheritance • When a class inherits from another class, there are three

Advantages of inheritance • When a class inherits from another class, there are three benefits: • (1) You can reuse the methods and data of the existing class (2) You can extend the existing class by adding new data and new methods (3) You can modify the existing class by overloading its methods with your own implementations

Rules for building a class hierarchy • Derived classes are special cases of base

Rules for building a class hierarchy • Derived classes are special cases of base classes • A derived class can also serve as a base class for new classes. • There is no limit on the depth of inheritance allowed in C++ (as far as it is within the limits of your compiler) • It is possible for a class to be a base class for more than one derived class

C++ Inheritance General Format for implementing the concept of Inheritance: class derived_classname: access specifier

C++ Inheritance General Format for implementing the concept of Inheritance: class derived_classname: access specifier baseclassname For example, if the base class is My. Class and the derived class is sample it is specified as: class sample: public My. Class The above makes sample have access to both public and protected variables of base class My. Class

Inheritance – Terminology and Notation in C++ • Base class (or parent) – inherited

Inheritance – Terminology and Notation in C++ • Base class (or parent) – inherited from • Derived class (or child) – inherits from the base class • Notation: class Student // base class {. . . }; class Under. Grad : public student { // derived class. . . }; 11

Back to the ‘is a’ Relationship • An object of a derived class 'is

Back to the ‘is a’ Relationship • An object of a derived class 'is a(n)' object of the base class • Example: – an Under. Grad is a Student – a Mammal is an Animal • A derived object has all of the characteristics of the base class 12

Inheritance and accessibility • A class inherits the behavior of another class and enhances

Inheritance and accessibility • A class inherits the behavior of another class and enhances it in some way • Inheritance does not mean inheriting access to another class’ private members

C++ Inheritance Reminder about public, private and protected access specifiers: 1 If a member

C++ Inheritance Reminder about public, private and protected access specifiers: 1 If a member or variables defined in a class is private, then they are accessible by members of the same class only and cannot be accessed from outside the class. 2 Public members and variables are accessible from outside the class. 3 Protected access specifier is a stage between private and public. If a member functions or variables defined in a class are protected, then they cannot be accessed from outside the class but can be accessed from the derived class.

Access Specifiers When deriving a class from a base class, the base class may

Access Specifiers When deriving a class from a base class, the base class may be inherited through public, protected or private inheritance. The type of inheritance is specified by the access- specifier. We hardly use protected or private inheritance, but public inheritance is commonly used. While using different type of inheritance, following rules are applied:

Access Specifiers üPublic Inheritance: When deriving a class from a public base class, public

Access Specifiers üPublic Inheritance: When deriving a class from a public base class, public members of the base class become public members of the derived class and protected members of the base class become protected members of the derived class. A base class's private members are never accessible directly from a derived class, but can be accessed through calls to the public and protected members of the base class.

Access Specifiers üProtected Inheritance: When deriving from a protected base class, public and protected

Access Specifiers üProtected Inheritance: When deriving from a protected base class, public and protected members of the base class become protected members of the derived class. üPrivate Inheritance: When deriving from private base class, public and protected members of the base class become private members of the derived class

Inheritance vs. Access Base class members How inherited base class members appear in derived

Inheritance vs. Access Base class members How inherited base class members appear in derived class x is inaccessible private: y private: z private: x protected: y public: z private base class private: x protected: y public: z protected base class x is inaccessible protected: y protected: z public base class x is inaccessible protected: y public: z private: x protected: y public: z 18

Inheritance vs. Access class Grade private members: char letter; float score; void calc. Grade();

Inheritance vs. Access class Grade private members: char letter; float score; void calc. Grade(); public members: void set. Score(float); float get. Score(); char get. Letter(); When Test class inherits from Grade class using public class access, it looks like this: class Test : public Grade private members: int num. Questions; float points. Each; int num. Missed; public members: Test(int, int); private members: int num. Questions: float points. Each; int num. Missed; public members: Test(int, int); void set. Score(float); float get. Score(); char get. Letter(); 19

Inheritance vs. Access class Grade private members: char letter; float score; void calc. Grade();

Inheritance vs. Access class Grade private members: char letter; float score; void calc. Grade(); public members: void set. Score(float); float get. Score(); char get. Letter(); When Test class inherits from Grade class using protected class access, it looks like this: class Test : protected Grade private members: int num. Questions; float points. Each; int num. Missed; public members: Test(int, int); private members: int num. Questions: float points. Each; int num. Missed; public members: Test(int, int); protected members: void set. Score(float); float get. Score(); float get. Letter(); 20

Inheritance vs. Access class Grade private members: char letter; float score; void calc. Grade();

Inheritance vs. Access class Grade private members: char letter; float score; void calc. Grade(); public members: void set. Score(float); float get. Score(); char get. Letter(); When Test class inherits from Grade class using private class access, it looks like this: class Test : private Grade private members: int num. Questions; float points. Each; int num. Missed; public members: Test(int, int); private members: int num. Questions: float points. Each; int num. Missed; void set. Score(float); float get. Score(); float get. Letter(); public members: Test(int, int); 21

Constructors and Destructors in Base and Derived Classes • Derived classes can have their

Constructors and Destructors in Base and Derived Classes • Derived classes can have their own constructors and destructors • When an object of a derived class is created, the base class’s constructor is executed first, followed by the derived class’s constructor • When an object of a derived class is destroyed, its destructor is called first, then that of the base class 22

C++ Inheritance Example: class My. Class { private: int x; public: My. Class(void) {

C++ Inheritance Example: class My. Class { private: int x; public: My. Class(void) { x=0; } void f(int n 1) { x= n 1*5; } void output(void) { cout<<x; } };

C++ Inheritance Example: class sample: public My. Class { private: int s 1; public:

C++ Inheritance Example: class sample: public My. Class { private: int s 1; public: sample(void) { s 1=0; } void f 1(int n 1) { s 1=n 1*10; } void output(void) { My. Class: : output(); cout << s 1; } };

C++ Inheritance Example: int main(void) { sample s; s. f(10); s. output(); s. f

C++ Inheritance Example: int main(void) { sample s; s. f(10); s. output(); s. f 1(20); s. output(); } The output of the above program is 50 200

Types of Inheritance 1. Single class Inheritance: Single inheritance is the one where you

Types of Inheritance 1. Single class Inheritance: Single inheritance is the one where you have a single base class and a single derived class. Class Employee Class Manager It is a Base class (super) it is a sub class (derived)

Types of Inheritance 2. Multilevel Inheritance: In Multi level inheritance, a class inherits properties

Types of Inheritance 2. Multilevel Inheritance: In Multi level inheritance, a class inherits properties from another derived class. Class Grandfather it is a Base class (super) of Class Father it is a sub class (derived) of Class Grandfather and base class of class Child Class Child derived class(sub) of class Father

Types of Inheritance 3. Multiple Inheritances: In Multiple inheritances, a derived class inherits from

Types of Inheritance 3. Multiple Inheritances: In Multiple inheritances, a derived class inherits from multiple base classes. It has properties of both the base classes. Class A Class C Class B Derived class Base class

Types of Inheritance 4. Hierarchical Inheritance: In hierarchical Inheritance, it's like an inverted tree.

Types of Inheritance 4. Hierarchical Inheritance: In hierarchical Inheritance, it's like an inverted tree. So multiple classes inherit from a single base class. It's quite analogous to the File system in a unix based system. Class A Class B Class D Class C

Types of Inheritance 5. Hybrid Inheritance: üIn this type of inheritance, we can have

Types of Inheritance 5. Hybrid Inheritance: üIn this type of inheritance, we can have mixture of number of inheritances but this can generate an error of using same name function from no of classes, which will bother the compiler to how to use the functions. üTherefore, it will generate errors in the program. This has known as ambiguity or duplicity. üAmbiguity problem can be solved by using virtual base classes

Types of Inheritance 5. Hybrid Inheritance: Class A Class B Class C Class D

Types of Inheritance 5. Hybrid Inheritance: Class A Class B Class C Class D

? Any Questions Please

? Any Questions Please

Board Question • Write a program in C++ to implement the following class hierarchy:

Board Question • Write a program in C++ to implement the following class hierarchy: Class student to obtain Roll Number, Class Test to obtain marks scored in two different subjects, Class Sports to obtain weight-age (marks) in sports and Class Result to calculate the total marks. The program must print the roll number, individual marks obtained in two subjects, sports and total marks. (15) • Enter the program and verify proper execution of the same on the Computer. (10) • Obtain a hard-copy of the program listing as well as output. (05)

Understanding Inheritance in Question Class Student Class Test Class Sports Class Result

Understanding Inheritance in Question Class Student Class Test Class Sports Class Result

#include<iostream. h> #include<conio. h> class student { protected: int roll_no; public: void get_no() {

#include<iostream. h> #include<conio. h> class student { protected: int roll_no; public: void get_no() { cout<<"Enter roll no : "; cin>>roll_no; } void put_no(void) { cout<<"Roll Number : "<<roll_no; } };

class test : public student { protected: float m 1, m 2; public: void

class test : public student { protected: float m 1, m 2; public: void get_marks() { cout<<"Enter marks of subject 1 : "; cin>>m 1; cout<<"Enter marks of subject 2 : "; cin>>m 2; } void put_marks(void) { cout<<"n. Marks obtained : Subject 1="<<m 1<<" and Subject 2="<<m 2; } };

class sports { protected: float score; public: void get_score() { cout<<"Enter marks of sports

class sports { protected: float score; public: void get_score() { cout<<"Enter marks of sports : "; cin>>score; } void put_score(void) { cout<<"n. Sports marks : "<<score; } };

class result : public test, public sports { protected: float total; public: void display(void)

class result : public test, public sports { protected: float total; public: void display(void) { cout<<"nn. Students details are as follows : n"; total=m 1+m 2+score; put_no(); put_marks(); put_score(); cout<<"n. Total score : "<<total; } };

void main() { clrscr(); result r; r. get_no(); r. get_marks(); r. get_score(); r. display();

void main() { clrscr(); result r; r. get_no(); r. get_marks(); r. get_score(); r. display(); getch(); }

Sample Output

Sample Output