Friday, 17 February 2023

Inheritance

 

Unit 4: Inheritance (12)          

4.1 Concept of inheritance

4.2 Base and Derived class

4.3 private, Public and Protected specifier

4.4 Derived class declaration

4.5 Member function overriding

4.6 Single, Multiple, Multilevel and Hybrid Inheritance

4.7 Ambiguity Problems in inheritance

4.8 Constructor in derived class

4.9 Extending operator overloading in derived class

 

Practical Works:

·       Create single level Inheritance

·       Create multiple inheritance

·       Create multilevel inheritance

·       Check the ambiguity problrms

 

4.1 Concept of inheritance

1. Inheritance is a process by which new classes called derived classes are created from existing classes called Base classes.

2. 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.

3. For example, a programmer can create a base class named fruit and define derived classes as Mango, Orange, Banana, etc each of them has some common characteristics like taste, price and season.  


 

                                                       Fig: Child classes of a class (inheritance)


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. 

Advantages of inheritance:

1.     Reusability: inheritance helps to reuse the previously written code. 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.

2.     Save time and effort: the concept of reusability achieved by inheritance saves programmer time and effort.

3.     Extendibility (enhancement) of the code: without changing the base class , we can add some more methods and features in derived class to extend the program. We can add any number of derived classes to upgrade the functionalities of the program.

 

 

4.2 Base and Derived class

Derived Class: The class that inherits properties from another class is called Sub class or Derived Class. 
Base Class: The class whose properties are inherited by sub class is called Base Class or Super class. 

Syntax:

Class base_Class_name

{

  …………..

    …………

};

Class derived_class_name : visibility_mode base_class_name

{

  Code for specific features of derived class

    …………

};

 

 

 

Example: write a program to illustrate the use of inheritance.

// C++ program to demonstrate implementation

// of Inheritance

  

#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 << '\n';

    cout << "Parent id is: " <<  obj1.id_p << '\n';

         

    return 0;

}

Output

Child id is 7

Parent id is 91

In the above program the ‘Child’ class is publicly inherited from the ‘Parent’ class so the public data members of the class ‘Parent’ will also be inherited by the class ‘Child’.

4.3 private, Public and Protected specifier

Visibility Modes of Inheritance

  1. 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.
  2. 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.

3.     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. 



Fig: visibility modes and its effects on inheritance

 

Note: The private members in the base class cannot be directly accessed in the derived class, while protected members can be directly accessed. For example, Classes B, C and D all contain the variables x, y and z in below example. It is just question of access.  

// C++ Implementation to show that a derived class

// doesn’t inherit access to private data members.

// However, it does inherit a full parent object.

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

};

 

4.4. Derived class declaration

1. in the declaration of derived class, you list the base classes of the derived class. The derived class inherits its members from these base classes.

2. The qualified_class_specifier must be a class that has been previously declared in a class declaration.

3. An access specifier is one of public, private, or protected.

4. The virtual keyword can be used to declare virtual base classes.

5. Following example shows the declaration of the derived class D and base classes V, B1, and B2. The class B1 is both a base class and a derived class because it is derived from class V and is a base class for D.

Class v {/*…..*/};

Class B1 : virtual public V {/*…..*/};

class B2 {/*…..*/};

class D : public B1, private B2 {/*…..*/};

 

4.5 Member function overriding

1. when a function, defined in the base class, is redefined in the derived class to fit its own needs, it is called function overriding.

2. Function overriding contains a function in the derived class which has the same name and argument types as the function in the base class but the definition is different.

3. Function overriding is the use of two or more functions having same name with same signature but defined one in base class and other in derived class.

Example: write a program to illustrate the use of function overriding

#include<iostream.h>

#include<conio.h>

class Person

{

protected:

    char name[20];

public:

    void read ()

      {

       cout<<”enter name of person:”;

       cin>>Name

      }

    Void Display()

     

      {

       cout<<”Name:”<<Name<<endl;

      

      }

 

 

;

Class Student: public person

 

 {

  int Roll;

  public:

  void read ()

      {

       cout<<”enter roll of Student:”;

       cin>>Roll;

      }

    Void Display()

     

      {

       cout<<”Roll No:”<<Roll<<endl;

      

      };

Void main ()

 

{

  Student st;

  St.Person::Read ();

  St.Read();

  Cout<<:”*******your records ******”<<endl;

  St.Person::Display();

  St.Display();

  Getch();

 

}

 

Output

Enter Name of Person: Ram

Enter Roll of Student:100

*********your records******

Name:Ram

Roll No.:100

4.6 Types of inheritance (Single, Multiple, Multilevel, Hierarchical and Hybrid Inheritance)

1. 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.



Syntax

class subclass_name : access_mode base_class

{

  // body of subclass

};

// C++ program to explain

// Single inheritance

#include<iostream>

using namespace std;

 

// base class

class Vehicle {

  public:

    Vehicle()

    {

      cout << "This is a Vehicle\n";

    }

};

 

// sub class derived from a single 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;

}

Output

This is a Vehicle

2. 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.



Syntax

class subclass_name : access_mode base_class1, access_mode base_class2, ....

{

  // body of subclass

};

Here, the number of base classes will be separated by a comma (‘, ‘) and access mode for every base class must be specified. 

// C++ program to explain

// multiple inheritance

#include<iostream>

using namespace std;

 

// first base class

class Vehicle {

  public:

    Vehicle()

    {

      cout << "This is a Vehicle\n";

    }

};

 

// second base class

class FourWheeler {

  public:

    FourWheeler()

    {

      cout << "This is a 4 wheeler Vehicle\n";

    }

};

 

// sub class derived from two base classes

class Car : public Vehicle, public FourWheeler {

 

};

 

// main function

int main()

{  

    // Creating object of sub class will

    // invoke the constructor of base classes.

    Car obj;

    return 0;

}

Output

This is a Vehicle

This is a 4 wheeler Vehicle

3. Multilevel Inheritance: In this type of inheritance, a derived class is created from another derived class.



// C++ program to implement

// Multilevel Inheritance

#include<iostream>

using namespace std;

 

// base class

class Vehicle

{

  public:

    Vehicle()

    {

      cout << "This is a Vehicle\n";

    }

};

 

// first sub_class derived from class vehicle

class fourWheeler: public Vehicle

{  public:

    fourWheeler()

    {

      cout << "Objects with 4 wheels are vehicles\n";

    }

};

// sub class derived from the derived base class fourWheeler

class Car: public fourWheeler {

   public:

     Car()

     {

       cout << "Car has 4 Wheels\n";

     }

};

 

// main function

int main()

{  

    // Creating object of sub class will

    // invoke the constructor of base classes.

    Car obj;

    return 0;

}

Output

This is a Vehicle

Objects with 4 wheels are vehicles

Car has 4 Wheels

4. 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.



// C++ program to implement

// Hierarchical Inheritance

#include<iostream>

using namespace std;

 

// base class

class Vehicle

{

  public:

    Vehicle()

    {

      cout << "This is a Vehicle\n";

    }

};

 

 

// first sub class

class Car: public Vehicle

{

 

};

 

// second sub class

class Bus: public Vehicle

{

     

};

 

// main function

int main()

{  

    // Creating object of sub class will

    // invoke the constructor of base class.

    Car obj1;

    Bus obj2;

    return 0;

}

Output

This is a Vehicle

This is a Vehicle

5. Hybrid (Virtual) Inheritance: Hybrid Inheritance is implemented by combining more than one type of inheritance. For example: Combining Hierarchical inheritance and Multiple Inheritance. 
Below image shows the combination of hierarchical and multiple inheritance:



// C++ program for Hybrid Inheritance

 

#include<iostream>

using namespace std;

 

// base class

class Vehicle

{

  public:

    Vehicle()

    {

      cout << "This is a Vehicle\n";

    }

};

 

//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

{

     

};

 

// main function

int main()

{  

    // Creating object of sub class will

    // invoke the constructor of base class.

    Bus obj2;

    return 0;

}

Output

This is a Vehicle

Fare of Vehicle

 

4.7 Ambiguity Problems in inheritance

When a function with same name and signature is defined in base class and derived class, problem of ambiguity arises. When the function is called with the help of object of derived class, then the question arises: “which version of the function is called?”. The problem is solved by using scope resolution operator (i.e. ::). By default, derived class gives priority to the function defined within it. So, base class version of the function is overridden by derived class version. To call base class version using object of derived class, we use scope resolution operator. This process is also called Ambiguity Resolution in inheritance.

An example program is shown below to demonstrate the concept of ambiguity resolution in inheritance.

class Base1{

    public:

        void greet(){

            cout<<"How are you?"<<endl;

        }

};

 

class Base2{

    public:

        void greet()

        {

            cout << "Kaise ho?" << endl;

        }

};

 

 

class Derived : public Base1, public Base2{

   int a;

   public:

    void greet(){

        Base2 :: greet();

    }

};

int main(){

  // Ambibuity 1

     Base1 base1obj;

     Base2 base2obj;

     base1obj.greet();

     base2obj.greet();

     Derived d;

     d.greet();

 

    return 0;

}

Another example of ambiguity resolution in inheritance is shown below.

class B{

    public:

        void say(){

            cout<<"Hello world"<<endl;

        }

};

 

class D: public B{

    int a;

    // D's new say() method will override base class's say() method

    public:

        void say()

        {

            cout << "Hello my beautiful people" << endl;

        }

};

int main(){

    // Ambibuity 2

    B b;

    b.say();

 

    D d;

    d.say();

 

    return 0;

}

 

4.8 Constructor in derived class

C++ program to the sequence of execution of constructor and destructor inheritance

#include<iostream>

using namespace std;

 

class parent //parent class

{

    public:

    parent() //constructor

    {

        cout << "Parent class Constructor\n";

    }

 

    ~parent()//destructor

    {

        cout << "Parent class Destructor\n";

    }

};

 

class child : public parent//child class

{

 

    public:

    child() //constructor

    {

    cout << "Child class Constructor\n";

    }

 

    ~ child() //destructor

    {

    cout << "Child class Destructor\n";

    }

};

 

int main()

{

    //automatically executes both child and parent class

    //constructors and destructors because of inheritance

    child c;

 

    return 0;

}

Another example of ambiguity resolution in inheritance is shown below.

class B{

    public:

        void say(){

            cout<<"Hello world"<<endl;

        }

};

 

class D: public B{

    int a;

    // D's new say() method will override base class's say() method

    public:

        void say()

        {

            cout << "Hello my beautiful people" << endl;

        }

};

Code Snippet 3:  Ambiguity Resolution in Inheritance Example Program 2

As shown in a code snippet 3,

  1. We have created a “B” class which consists of public member function “say”. The function “say” will print “hello world”
  2. We have created a “D” class that is inheriting the “B” class. The “D” class consists of the public member function “say”. The function “say” will print “Hello my beautiful people”

The main thing to note here is that both “B” and “D” classes have the same function “say”, So if the class “D” will call the function “say” it will override the base class “say” method because compiler by default run the method which is already written in its own body. But if the function “say” was not present in the class “D” then the compiler will run the method of the class “B”.

The code of the main function is shown below,

int main(){

    // Ambibuity 2

    B b;

    b.say();

 

    D d;

    d.say();

 

    return 0;

}

 

 

 



 

No comments:

Post a Comment

Teaching Method in ICT Education | Syllabus | Seven Semester | BICTE

  Course Title: Teaching Method in ICT Education Course No.: ICT. Ed. 478                                            Nature of ...