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
    COMP2111
    Progress0 / 23 topics
    Topics
    1. Introduction to object oriented design2. History and advantages of object oriented design3. Introduction to object oriented programming concepts4. Classes and objects5. Data encapsulation6. Constructors and destructors7. Access modifiers8. Const vs non-const functions9. Static data members & functions10. Function overloading11. Operator overloading12. Identification of classes and their relationships13. Composition and aggregation14. Inheritance15. Multiple inheritance16. Polymorphism17. Abstract classes and interfaces18. Generic programming concepts19. Function & class templates20. Standard template library21. Object streams22. Data and object serialization using object streams23. Exception handling
    COMP2111›Inheritance
    Object Oriented ProgrammingTopic 14 of 23

    Inheritance

    8 minread
    1,307words
    Intermediatelevel

    Inheritance in C++

    Inheritance is one of the fundamental concepts of Object-Oriented Programming (OOP), allowing a new class (derived class) to inherit properties and behaviors (methods) from an existing class (base class). It helps to model hierarchical relationships between objects and promotes code reusability, which is a key benefit of OOP.

    What is Inheritance?

    • Inheritance is a mechanism in which a new class (child or derived class) acquires the properties and behaviors (attributes and methods) of an existing class (parent or base class).
    • It allows you to create a new class by building on an existing class, rather than writing everything from scratch.
    • Inheritance represents an "is-a" relationship between the base class and the derived class. For example, a Dog is an Animal, or a Car is a Vehicle.

    Types of Inheritance in C++:

    1. Single Inheritance: A derived class inherits from a single base class.
    2. Multiple Inheritance: A derived class inherits from more than one base class.
    3. Multilevel Inheritance: A derived class inherits from a base class, and then another class inherits from that derived class.
    4. Hierarchical Inheritance: Multiple classes inherit from a single base class.
    5. Hybrid Inheritance: A combination of more than one type of inheritance.

    Basic Syntax of Inheritance:

    The syntax to define inheritance in C++ is as follows:

    class DerivedClass : access_specifier BaseClass {
        // Derived class members
    };
    
    • DerivedClass is the class that will inherit from the base class.
    • BaseClass is the class that is being inherited from.
    • Access Specifier determines the visibility of the base class members in the derived class:
      • public: All public members of the base class are accessible as public members in the derived class.
      • protected: All protected members of the base class are accessible as protected members in the derived class.
      • private: All members of the base class are inaccessible in the derived class (not typically used for inheritance).

    Example: Basic Inheritance (Single Inheritance)

    Let's consider a simple example where we have a base class Animal, and a derived class Dog.

    #include <iostream>
    using namespace std;
    
    // Base class
    class Animal {
    public:
        void eat() {
            cout << "This animal eats food." << endl;
        }
    };
    
    // Derived class
    class Dog : public Animal {
    public:
        void bark() {
            cout << "The dog barks." << endl;
        }
    };
    
    int main() {
        Dog myDog;
        myDog.eat();   // Inherited function from Animal class
        myDog.bark();  // Function of Dog class
        return 0;
    }
    

    Explanation:

    • The Dog class is derived from the Animal class using the public access specifier.
    • The Dog class inherits the eat() method from the Animal class.
    • The Dog class has its own method bark().
    • The main() function creates an object myDog of type Dog and calls both the inherited eat() method and the bark() method.

    Access Specifiers in Inheritance

    1. Public Inheritance:

    • In public inheritance, the public members of the base class remain public in the derived class, and protected members remain protected.
    class Base {
    public:
        int x;
        void show() {
            cout << "x = " << x << endl;
        }
    };
    
    class Derived : public Base {
    public:
        void set(int val) {
            x = val;  // x is accessible because it's public in Base
        }
    };
    

    2. Protected Inheritance:

    • In protected inheritance, the public and protected members of the base class become protected in the derived class.
    class Base {
    public:
        int x;
        void show() {
            cout << "x = " << x << endl;
        }
    };
    
    class Derived : protected Base {
    public:
        void set(int val) {
            x = val;  // x is accessible but is protected in Derived
        }
    };
    

    3. Private Inheritance:

    • In private inheritance, both the public and protected members of the base class become private in the derived class. This is less common because it makes the base class's functionality less accessible.
    class Base {
    public:
        int x;
        void show() {
            cout << "x = " << x << endl;
        }
    };
    
    class Derived : private Base {
    public:
        void set(int val) {
            x = val;  // x is now private in Derived
        }
    };
    

    Constructor and Destructor in Inheritance

    • Base Class Constructor: The constructor of the base class is called before the constructor of the derived class.
    • Base Class Destructor: When the derived class object is destroyed, the base class destructor is automatically called.

    Example: Constructor in Inheritance

    #include <iostream>
    using namespace std;
    
    class Animal {
    public:
        Animal() {
            cout << "Animal Constructor Called" << endl;
        }
    };
    
    class Dog : public Animal {
    public:
        Dog() {
            cout << "Dog Constructor Called" << endl;
        }
    };
    
    int main() {
        Dog myDog;
        // Output:
        // Animal Constructor Called
        // Dog Constructor Called
        return 0;
    }
    

    Explanation:

    • The base class Animal constructor is called first, followed by the derived class Dog constructor.

    Overriding Functions in Inheritance

    In inheritance, a derived class can override methods of the base class to provide its own implementation. This is called method overriding. You use the same function name and parameters, but you provide a new implementation in the derived class.

    Example: Function Overriding

    #include <iostream>
    using namespace std;
    
    class Animal {
    public:
        virtual void sound() {
            cout << "Animal makes a sound" << endl;
        }
    };
    
    class Dog : public Animal {
    public:
        void sound() override {
            cout << "Dog barks" << endl;
        }
    };
    
    int main() {
        Animal* animal = new Dog();
        animal->sound();  // Output: Dog barks
        return 0;
    }
    

    Explanation:

    • The sound() function in the Animal class is overridden in the Dog class.
    • The virtual keyword allows the derived class method to override the base class method, and override helps ensure that the method is correctly overriding a base class function.
    • When animal->sound() is called, the derived class (Dog) version of the function is executed, even though the pointer is of type Animal. This is polymorphism in action.

    Multiple Inheritance in C++

    In C++, a derived class can inherit from more than one base class. This is known as multiple inheritance.

    Example: Multiple Inheritance

    #include <iostream>
    using namespace std;
    
    class Animal {
    public:
        void eat() {
            cout << "Eating food" << endl;
        }
    };
    
    class Mammal {
    public:
        void breathe() {
            cout << "Breathing air" << endl;
        }
    };
    
    class Dog : public Animal, public Mammal {
    public:
        void bark() {
            cout << "Barking" << endl;
        }
    };
    
    int main() {
        Dog dog;
        dog.eat();       // From Animal class
        dog.breathe();   // From Mammal class
        dog.bark();      // From Dog class
        return 0;
    }
    

    Explanation:

    • The Dog class inherits from both Animal and Mammal.
    • It can access methods from both base classes (eat() from Animal and breathe() from Mammal), as well as its own method bark().

    Summary of Inheritance:

    • Inheritance allows a class (derived class) to inherit the attributes and methods of another class (base class).
    • It promotes code reusability and helps in modeling hierarchical relationships (e.g., Dog is a type of Animal).
    • There are several types of inheritance: single, multiple, multilevel, hierarchical, and hybrid.
    • Access specifiers (public, protected, private) control the visibility of the base class members in the derived class.
    • The derived class can override the base class methods to provide its own implementation.
    • Constructors of the base class are called before the derived class constructor, and destructors are called in the reverse order.

    Inheritance helps organize code and allows for the creation of more complex systems by building on existing functionality.

    Previous topic 13
    Composition and aggregation
    Next topic 15
    Multiple inheritance

    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 time8 min
      Word count1,307
      Code examples0
      DifficultyIntermediate