Introduction to inheritance and different types of inheritance
76 views
51 slides
Jun 21, 2024
Slide 1 of 51
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
About This Presentation
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a new class (subclass) to inherit properties and methods from an existing class (superclass). This mechanism promotes code reusability, improves maintainability, and establishes a natural hierarchical relationship ...
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a new class (subclass) to inherit properties and methods from an existing class (superclass). This mechanism promotes code reusability, improves maintainability, and establishes a natural hierarchical relationship between classes.
Object Relationship Object oriented programming generally support 4 types of relationships that are: Is-a relationship Inheritance Part-of relationship Composition has-a relationship Aggregation and Association
Inheritance : Is-a Relationship Sometimes, one class is an extension of another class. inheritance is an is-a relationship . We use inheritance only if an is-a relationship is present between the two classes. It is just like saying that “A is type of B”. For example is “Apple is a fruit”, “Ferrari is a car”. A car is a vehicle. Orange is a fruit. A surgeon is a doctor. A dog is an animal.
Inheritance The technique of deriving a new class from an old one is called inheritance Capability of a class to derive properties and characteristics from another class. The extended (or child) class contains all the features of its base (or parent) class, and may additionally have some unique features of its own.
Inheritance cont. Sub Class : The class that inherits properties from another class is called Sub class or Derived Class. Super Class : The class whose properties are inherited by sub class is called Base Class or Super class. For example,
Inheritance - Real World Scenario HOD is a staff member of college. All teachers are staff member of college.
Example #include <bits/stdc++.h> using namespace std; //Base class class Parent { public: int id_p; }; // Sub class inheriting from Base Class(Parent) class Child : public Parent { public: int id_c; }; //main function int main() { Child obj1; // An object of class child has all data members // and member functions of class parent obj1.id_c = 7; obj1.id_p = 91; cout << "Child id is " << obj1.id_c << endl; cout << "Parent id is " << obj1.id_p << endl; return 0; }
Example // C++ program to demonstrate inheritance #include <iostream> using namespace std; // base class class Animal { public: void eat() { cout << "I can eat!" << endl; } void sleep() { cout << "I can sleep!" << endl; } }; // derived class class Dog : public Animal { public: void bark() { cout << "I can bark! Woof woof!!" << endl; } }; int main() { // Create object of the Dog class Dog dog1; // Calling members of the base class dog1.eat(); dog1.sleep(); // Calling member of the derived class dog1.bark(); return 0; } I can eat! I can sleep! I can bark! Woof woof!! Output
Why and when to use inheritance? Consider a group of vehicles. You need to create classes for Bus, Car and Truck. The methods fuelAmount(), capacity(), applyBrakes() will be same for all of the three classes.
Why and when to use inheritance? You can clearly see that above process results in duplication of same code 3 times. This increases the chances of error and data redundancy. To avoid this type of situation, inheritance is used. If we create a class Vehicle and write these three functions in it and inherit the rest of the classes from the vehicle class, then we can simply avoid the duplication of data and increase re-usability.
Why and when to use inheritance?
Implementing inheritance in C++ Syntax: class subclass_name : access_mode base_class_name { //body of subclass };
Modes of Inheritance Public mode : If we derive a sub class from a public base class. Then the public member of the base class will become public in the derived class and protected members of the base class will become protected in derived class. Protected mode : If we derive a sub class from a Protected base class. Then both public member and protected members of the base class will become protected in derived class. Private mode : If we derive a sub class from a Private base class. Then both public member and protected members of the base class will become Private in derived class.
Mode of Inheritance class A { public: int x; protected: int y; private: int z; }; class B : public A { // x is public // y is protected // z is not accessible from B }; class C : protected A { // x is protected // y is protected // z is not accessible from C }; class D : private A // 'private' is default for classes { // x is private // y is private // z is not accessible from D };
Mode of Inheritance
Types of Inheritance in C++ Single Inheritance Multiple Inheritance Multilevel Inheritance Hierarchical Inheritance Hybrid (Virtual) Inheritance
Single Inheritance In single inheritance, a class is allowed to inherit from only one class. i.e. one sub class is inherited by one base class only.
Single Inheritance (Continue..) Syntax: class subclass_name : access_mode base_class { //body of subclass }; // sub class derived from two base classes class Car: public Vehicle{ }; // main function int main() { // creating object of sub class will // invoke the constructor of base classes Car obj; return 0; } #include <iostream> using namespace std; // base class class Vehicle { public: Vehicle() { cout << "This is a Vehicle" << endl; } };
Multiple Inheritance Multiple Inheritance is a feature of C++ where a class can inherit from more than one classes. i.e one sub class is inherited from more than one base classes .
Multiple Inheritance (Continue..) Syntax: class subclass_name : access_mode base_class1, access_mode base_class2, ....{//body of subclass}; class output : public stud, public extracurriculam { int tot, avg; public: void display() { tot = (m1 + m2 + xm); avg = tot / 3; cout << "\n\n\tRoll No : " << roll << "\n\tTotal : " << tot; cout << "\n\tAverage : " << avg; } }; int main() { output O; O.get(); O.getsm(); O.display(); } class stud { protected: int roll, m1, m2; public: void get() { cout << "Enter the Roll No.: "; cin >> roll; cout << "Enter the two highest marks: "; cin >> m1 >> m2; } }; class extracurriculam { protected: int xm; public: void getsm() { cout << "\nEnter the mark for Extra Curriculam Activities: "; cin >> xm; } }
Multilevel Inheritance In this type of inheritance, a derived class is created from another derived class.
Multilevel Inheritance (Continue..) class derived2 : public derived { void display3() { cout << "\n2nd Derived class content."; } }; int main() { derived2 D; //D.display3(); D.display2(); D.display1(); } #include <iostream> using namespace std; class base { public: void display1() { cout << "\nBase class content."; } }; class derived : public base { public: void display2() { cout << "1st derived class content."; } };
Hierarchical Inheritance In this type of inheritance, more than one sub class is inherited from a single base class. i.e. more than one derived class is created from a single base class.
Hierarchical Inheritance (Continue..) include <iostream> #include <string.h> using namespace std; class member { char gender[10]; int age; public: void get() { cout << "Age: "; cin >> age; cout << "Gender: "; cin >> gender; } void disp() { cout << "Age: " << age << endl; cout << "Gender: " << gender << endl; }}; class stud : public member { char level[20]; public: void getdata() { member::get(); cout << "Class: "; cin >> level; } void disp2() { member::disp(); cout << "Level: " << level << endl; } }; class staff : public member { float salary; public: void getdata() { member::get(); cout << "Salary: Rs."; cin >> salary; } void disp3() { member::disp(); cout << "Salary: Rs." << salary << endl; Student Enter data Age: 12 Gender: Female Class: 10 Displaying data Age: 12 Gender: Female Output int main() { member M; staff S; stud s; cout << "Student" << endl; cout << "Enter data" << endl; s.getdata(); cout << endl << "Displaying data" << endl; s.disp(); cout << endl << "Staff Data" << endl; cout << "Enter data" << endl; S.getdata(); cout << endl << "Displaying data" << endl; S.disp(); } Staff Data Enter data Age: 12 Gender: male Salary: Rs.100000 Displaying data Age: 12 Gender: male
Hybrid (Virtual) Inheritance Hybrid Inheritance is implemented by combining more than one type of inheritance. For example: Combining Hierarchical inheritance and Multiple Inheritance.
Hybrid Inheritance (Continue..) // base class class Vehicle { public: Vehicle() { cout << "This is a Vehicle" << endl; } }; //base class class Fare { public: Fare() { cout<<"Fare of Vehicle\n"; } }; // first sub class class Car: public Vehicle { }; // second sub class class Bus: public Vehicle, public Fare { }; This is a Vehicle Fare of Vehicle Output // main function int main() { // creating object of sub class will // invoke the constructor of base class Bus obj2; return 0; }
Order of constructor and Destructor call Whenever we create an object of a class, the default constructor of that class is invoked automatically to initialize the members of the class. If we inherit a class from another class and create an object of the derived class, it is clear that the default constructor of the derived class will be invoked but before that the default constructor of all of the base classes will be invoke, i.e the order of invokation is that the base class’s default constructor will be invoked first and then the derived class’s default constructor will be invoked.
Order of constructor and Destructor call
Example #include <iostream> using namespace std; // base class class Parent { public: // base class constructor Parent() { cout << "Inside base class" << endl; } }; // sub class class Child : public Parent { public: //sub class constructor Child() { cout << "Inside sub class" << endl; } }; Inside base class Inside sub class Output // main function int main() { // creating object of sub class Child obj; return 0; }
Concept: Base class Default Constructor in Derived class Constructors ! class Base { int x; public: // default constructor Base() { cout << "Base default constructor\n"; } }; class Derived : public Base { int y; public: // default constructor Derived() { cout << "Derived default constructor\n"; } // parameterized constructor Derived(int i) { cout << "Derived parameterized constructor\n"; } }; Base default constructor Base default constructor Derived default constructor Base default constructor Derived parameterized constructor Output int main() { Base b; Derived d1; Derived d2(10); } Example
Concept: Calling parameterized constructor of base class in derived class constructor ! To call the parameterized constructor of base class when derived class’s parameterized constructor is called, you have to explicitly specify the base class’s parameterized constructor in derived class
Concept: Calling parameterized constructor of base class in derived class constructor! class Base { int x; public: // parameterized constructor Base(int i) { x = i; cout << "Base Parameterized Constructor\n"; } }; class Derived : public Base { int y; public: // parameterized constructor Derived(int j):Base(j) { y = j; cout << "Derived Parameterized Constructor\n"; } }; Base Parameterized Constructor Derived Parameterized Constructor Output int main() { Derived d(10) ; } Example
Important Points Whenever the derived class’s default constructor is called, the base class’s default constructor is called automatically. To call the parameterized constructor of base class inside the parameterized constructor of sub class, we have to mention it explicitly.
Exercise Create two classes named Mammals and MarineAnimals. Create another class named BlueWhale which inherits both the above classes. Now, create a function in each of these classes which prints "I am mammal", "I am a marine animal" and "I belong to both the categories: Mammals as well as Marine Animals" respectively. Now, create an object for each of the above class and try calling 1 - function of Mammals by the object of Mammal 2 - function of MarineAnimal by the object of MarineAnimal 3 - function of BlueWhale by the object of BlueWhale 4 - function of each of its parent by the object of BlueWhale Types of Inheritance = ?? Write a Basic Sekeletone
Exercise Create a base class named Person with name, age, and gender as its data members. Define a constructor to initialize the data members and a function display() to display the details of the person. Create a derived class named Employee which inherits Person class. Define empid and salary as its data members. Define a constructor to initialize the data members and override the display() function to display the details of the employee. Create another derived class named Manager which inherits Employee class. Define department as its data member. Define a constructor to initialize the data members and override the display() function to display the details of the manager. Create an object for Person, Employee, and Manager classes and call their display() functions. Types of Inheritance = ?? Write a Basic Sekeletone
Data Code Hiding
Polymorphism Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and morphs means forms. So polymorphism means many forms. Polymorphism is a feature of OOPs that allows the object to behave differently in different conditions. we can define polymorphism as the ability of a message to be displayed in more than one form. First concept given by Hindley and Milner. The basic idea behind the polymorphism is that compiler does not which function to call at compile time.
Polymorphism-contd. A real-life example of polymorphism, a person at the same time can have different characteristics. Like a man at the same time is a father, a husband, an employee. So the same person posses different behavior in different situations. This is called polymorphism.
Polymorphism-contd.
Real life example of Polymorphism Suppose if you are in class room that time you behave like a student, when you are in market at that time you behave like a customer, when you at your home at that time you behave like a son or daughter, Here one person have different-different behaviors.
Polymorphism Importance Polymorphism saves the programmer a lot of time in re-creating code. You don't want to have to write completely different modules for every possible permutation. For example, if you had methods for tree growth, it would be hard to have to write a specific growth method for maple, spruce, pine, etc. Instead, you can have a growth function that spans across all tree types.
Difference between Inheritance & Polymorphism S.NO INHERITANCE POLYMORPHISM 1. Inheritance is one in which a new class is created (derived class) that inherits the features from the already existing class(Base class). Whereas polymorphism is that which can be defined in multiple forms. 2. It is basically applied to classes. Whereas it is basically applied to functions or methods. 3. Inheritance supports the concept of reusability and reduces code length in object-oriented programming. Polymorphism allows the object to decide which form of the function to implement at compile-time (overloading) as well as run-time (overriding). 4. Inheritance can be single, hybrid, multiple, hierarchical and multilevel inheritance. Whereas it can be compiled-time polymorphism (overload) as well as run-time polymorphism (overriding).
Type of Polymorphism Static / Compile time polymorphism Dynamic / Run time polymorphism
Static / Compile time polymorphism It is also called Early Binding It happens where more than one methods share the same name with different parameters or signature and different return type. It is known as Early Binding because the compiler is aware of the functions with same name and also which overloaded function is to be called is known at compile time.
Static / Compile time polymorphism using namespace std; class Geeks { public: // function with 1 int parameter void func(int x) { cout << "value of x is " << x << endl; } // function with same name but 1 double parameter void func(double x) { cout << "value of x is " << x << endl; } // function with same name and 2 int parameters void func(int x, int y) { cout << "value of x and y is " << x << ", " << y << endl; } }; int main() { Geeks obj1; // Which function is called will depend on the parameters passed // The first 'func' is called obj1.func(7); // The second 'func' is called obj1.func(9.132); // The third 'func' is called obj1.func(85,64); return 0; }
Dynamic / Run time polymorphism This refers to the entity which changes its form depending on circumstances at runtime. Method Overriding uses runtime Polymorphism. Runtime Polymorphism is done using virtual and inheritance. It is also called Late Binding.
Dynamic / Run time polymorphism include <bits/stdc++.h> using namespace std; class base { public: void print () { cout<< "print base class" <<endl; } void show () { cout<< "show base class" <<endl; } }; class derived:public base { public: void print () //print () is already virtual function in derived class, we could also declared as virtual void print () explicitly { cout<< "print derived class" <<endl; } void show () { cout<< "show derived class" <<endl; } }; //main function int main() { base *bptr; derived d; bptr = &d; //virtual function, binded at runtime (Runtime polymorphism) bptr->print(); // Non-virtual function, binded at compile time bptr->show(); return 0; }
Virtual Function If it is necessary to use a single pointer to refer to all the different classes’ objects. This is because we will have to create a pointer to the base class that refers to all the derived objects. But, when the base class pointer contains the derived class address, the object always executes the base class function. For resolving this problem, we use the virtual function.
The vtable for the base class is straightforward. In the case of the derived class, only function1_virtual is overridden. Hence we see that in the derived class vtable, function pointer for function1_virtual points to the overridden function in the derived class. On the other hand function pointer for function2_virtual points to a function in the base class. Thus in the above program when the base pointer is assigned a derived class object, the base pointer points to _vptr of the derived class. So when the call b->function1_virtual() is made, the function1_virtual from the derived class is called and when the function call b->function2_virtual() is made, as this function pointer points to the base class function, the base class function is called.
Case-Study Define a class batsman with the following specifications: Private members: bcode 4 digits code number bname 20 characters innings, notout, runs integer type batavg it is calculated according to the formula – batavg =runs/(innings-notout) calcavg() Function to compute batavg Public members: readdata() Function to accept value from bcode, name, innings, notout and invoke the function calcavg() displaydata() Function to display the data members on the screen.