ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Object Oriented Programming
    CC-211
    Progress0 / 24 topics
    Topics
    1. Object-Oriented Design: History and Advantages2. Object-Oriented Programming: Terminology and Features3. Classes and Objects4. Data Encapsulation5. Constructors and Destructors6. Access Modifiers7. Const vs Non-Const Functions8. Static Data Members and Functions9. Function Overloading10. Operator Overloading11. Identification of Classes and Their Relationships12. Composition13. Aggregation14. Inheritance15. Multiple Inheritances16. Polymorphism17. Abstract Classes18. Interfaces19. Generic Programming Concepts20. Function Templates21. Class Templates22. Standard Template Library23. Object Streams: Data and Object Serialization24. Exception Handling
    CC-211›Inheritance
    Object Oriented ProgrammingTopic 14 of 24

    Inheritance

    7 minread
    1,271words
    Intermediatelevel

    Inheritance in Object-Oriented Programming (OOP)

    Inheritance is one of the core concepts of object-oriented programming (OOP). It allows a new class to inherit properties and behaviors (i.e., attributes and methods) from an existing class. The class that is inherited from is known as the base class (or parent class, superclass), and the class that inherits from the base class is known as the derived class (or child class, subclass).

    Inheritance enables the creation of a hierarchical relationship between classes, promoting code reusability, extensibility, and maintainability.

    Key Concepts of Inheritance

    • Base Class (Parent Class): The class whose properties and behaviors are inherited by another class. It is the "general" or "generic" class.
    • Derived Class (Child Class): The class that inherits from the base class and may add or modify functionalities. It is more specific than the base class.
    • "Is-a" Relationship: Inheritance models the "is-a" relationship. For example, a Car is a Vehicle, meaning that Car inherits from Vehicle.
    • Access to Members: The derived class inherits the public and protected members of the base class, but not its private members (though private members can be accessed indirectly via public or protected member functions).

    Types of Inheritance

    1. Single Inheritance: A class inherits from a single base class.

      Example: A Dog class inherits from an Animal class.

      class Animal {
      public:
          void eat() { cout << "Eating" << endl; }
      };
      
      class Dog : public Animal {
      public:
          void bark() { cout << "Barking" << endl; }
      };
      
    2. Multiple Inheritance: A class can inherit from more than one base class.

      Example: A FlyingCar class could inherit from both Car and FlyingMachine.

      class Car {
      public:
          void drive() { cout << "Driving" << endl; }
      };
      
      class FlyingMachine {
      public:
          void fly() { cout << "Flying" << endl; }
      };
      
      class FlyingCar : public Car, public FlyingMachine {
      };
      
    3. Multilevel Inheritance: A class inherits from a derived class, creating a multi-level chain.

      Example: Grandchild inherits from Child, which inherits from Parent.

      class Parent {
      public:
          void speak() { cout << "Speaking from Parent" << endl; }
      };
      
      class Child : public Parent {
      public:
          void play() { cout << "Playing from Child" << endl; }
      };
      
      class Grandchild : public Child {
      public:
          void dance() { cout << "Dancing from Grandchild" << endl; }
      };
      
    4. Hierarchical Inheritance: Multiple derived classes inherit from a single base class.

      Example: Both Dog and Cat inherit from the Animal class.

      class Animal {
      public:
          void eat() { cout << "Eating" << endl; }
      };
      
      class Dog : public Animal {
      public:
          void bark() { cout << "Barking" << endl; }
      };
      
      class Cat : public Animal {
      public:
          void meow() { cout << "Meowing" << endl; }
      };
      
    5. Hybrid Inheritance: A combination of two or more of the above types of inheritance.

    Advantages of Inheritance

    1. Code Reusability: The derived class can reuse the methods and attributes of the base class, reducing redundancy in code. This makes it easier to maintain and extend the codebase.
    2. Extensibility: New functionality can be added to derived classes without modifying the base class. This makes it easier to extend systems over time.
    3. Hierarchical Organization: Inheritance allows a natural organization of classes that reflects real-world relationships. For instance, Car inherits from Vehicle, which might also have a Truck and Bus as subclasses.
    4. Data Abstraction: Inheritance allows you to define a base class with general behaviors and then use derived classes for more specific details. This helps in modeling real-world systems more abstractly.

    Disadvantages of Inheritance

    1. Tight Coupling: The derived class depends heavily on the base class. Changes in the base class may affect the derived classes, which can lead to issues if the system grows complex.
    2. Reduced Flexibility: Inheritance, if not used properly, can lead to fragile code and excessive dependency between the base and derived classes.
    3. Increased Complexity: Overuse of inheritance can make a codebase more complex and harder to understand. Excessive hierarchy can lead to problems with managing and debugging the code.

    Example of Inheritance in C++

    Let's look at an example where a Car class inherits from a more general Vehicle class.

    Example Code:

    #include <iostream>
    using namespace std;
    
    class Vehicle {
    public:
        string brand;
        int year;
    
        // Constructor
        Vehicle(string b, int y) : brand(b), year(y) {}
    
        // Method
        void displayInfo() {
            cout << "Brand: " << brand << ", Year: " << year << endl;
        }
    };
    
    // Derived class from Vehicle
    class Car : public Vehicle {
    public:
        int numDoors;
    
        // Constructor for Car
        Car(string b, int y, int doors) : Vehicle(b, y), numDoors(doors) {}
    
        // Method specific to Car
        void displayCarInfo() {
            displayInfo();  // Call base class method
            cout << "Number of doors: " << numDoors << endl;
        }
    };
    
    int main() {
        // Creating an object of the derived class Car
        Car myCar("Toyota", 2020, 4);
    
        // Displaying car information
        myCar.displayCarInfo();
    
        return 0;
    }
    

    Explanation:

    1. Base Class (Vehicle): The Vehicle class has attributes brand and year, and a method displayInfo() to display the basic details of the vehicle.

    2. Derived Class (Car): The Car class inherits from Vehicle and adds an additional attribute numDoors. It also has a method displayCarInfo() that calls the base class method displayInfo() and adds its own functionality.

    3. Constructor Inheritance: The constructor of Car calls the constructor of Vehicle to initialize the brand and year attributes.

    4. Method Inheritance: The derived class Car inherits the displayInfo() method from Vehicle and uses it in displayCarInfo().

    Output:

    Brand: Toyota, Year: 2020
    Number of doors: 4
    

    Access Specifiers in Inheritance

    In C++, inheritance can be classified based on the access specifiers used:

    1. Public Inheritance (public):

      • The public and protected members of the base class remain accessible in the derived class.
      • The derived class is-a the base class, and objects of the derived class can be used where the base class type is expected.
      class Derived : public Base {
          // Public members of Base become public in Derived
          // Protected members of Base become protected in Derived
      };
      
    2. Protected Inheritance (protected):

      • The public and protected members of the base class become protected in the derived class. Derived class objects cannot be used where the base class type is expected.
      class Derived : protected Base {
          // Public and protected members of Base become protected in Derived
      };
      
    3. Private Inheritance (private):

      • The public and protected members of the base class become private in the derived class. Derived class objects cannot be used where the base class type is expected.
      • It is less common and is used when the relationship is more about implementation rather than a "is-a" relationship.
      class Derived : private Base {
          // Public and protected members of Base become private in Derived
      };
      

    Summary

    • Inheritance allows the creation of new classes that are based on existing ones, promoting code reuse, extensibility, and the modeling of real-world relationships.
    • It supports the "is-a" relationship, where a derived class is a specialized version of the base class.
    • Types of inheritance include single, multiple, multilevel, hierarchical, and hybrid inheritance.
    • While inheritance offers many advantages like reusability and maintainability, it also introduces challenges such as tight coupling and increased complexity when overused.
    Previous topic 13
    Aggregation
    Next topic 15
    Multiple Inheritances

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time7 min
      Word count1,271
      Code examples0
      DifficultyIntermediate