6 Inheritance And Polymorphism

Object Oriented Programming · Unit 6

Inheritance and Polymorphism

Exam-focused notes for Inheritance and Polymorphism (Object Oriented Programming, BIT153): what the TU syllabus asks and how it has actually been tested, with 10 solved past questions from this unit.

Inheritance and Polymorphism in short

Inheritance lets one class build on another. It is the main way C++ supports code reuse and a natural "is-a" relation between classes.

Inheritance and Polymorphism: notes

Inheritance definition and purpose

Inheritance is the process by which a new class gets the properties and behaviour of an existing class. The new class is the derived class (child). The existing class is the base class (parent).

Purposes:

  • Code reuse: write common code once in the base class.
  • It models real relations, such as a Student is a Person.
  • The derived class can add new members or change inherited behaviour.
  • It makes programs easier to extend and maintain.

The syntax is:

class Derived : access_specifier Base { /* new members */ };

Single-level inheritance

In single inheritance, a derived class has only one base class.

class Person {
protected:
    string name;
public:
    void setName(string n) { name = n; }
};
class Student : public Person {
    int roll;
public:
    void setRoll(int r) { roll = r; }
    void show() { cout << name << " " << roll << endl; }
};

int main() {
    Student s;
    s.setName("Hari");
    s.setRoll(7);
    s.show();
}

Multi-level inheritance

In multilevel inheritance, a class is derived from a class which is itself derived from another. It forms a chain: A to B to C.

class Animal { public: void eat() { cout << "eats\n"; } };
class Dog : public Animal { public: void bark() { cout << "barks\n"; } };
class Puppy : public Dog { public: void weep() { cout << "weeps\n"; } };

int main() {
    Puppy p;
    p.eat(); p.bark(); p.weep();   // all three available
}

Puppy gets members of both Dog and Animal.

What this unit covers

  • Inheritance definition and purpose
  • Single-level inheritance
  • Multi-level inheritance
  • Multiple inheritance
  • Hybrid inheritance
  • Public, private, and protected inheritance
  • Virtual base class and ambiguity resolution
  • Aggregation versus inheritance

Multi-level inheritance

2082 · 10 marks

Explain inheritance with suitable example.Differentiate between single, multiple, and hybrid inheritance.Write a program to show constructor invocation order in multilevel inheritance.[1+4+5]

Inheritance is an Object-Oriented Programming (OOP) concept where a new class (called the derived class or child class) acquires the properties and behaviors (data members and member functions) of an existing class (called the base class or parent class). Key Benefits: - Code reusability - Extens...

Open this answer on its own page →

2080.1 · 10 marks

Differentiate between single level inheritance and multiple inheritance?Write a C++ program to calculate the percentage of a student using multi-level inheritance. Accept the marks of three subjects in base class "Capture". Derive class "Total" from "capture" which should include a function to find the total marks obtained and derive class "Final" from "Total" which should calculate and display the percentage of student.[3+7]

Feature Single Level Inheritance Multiple Inheritance --------- Definition A derived class inherits from only one base class A derived class inherits from two or more base classes Syntax class B : public A {} class C : public A, public B {} Complexity Simple and easy to implement More complex; ca...

Open this answer on its own page →

Virtual base class and ambiguity resolution

2082 · 5 marks

Explain ambiguity problem in multiple inheritance with example. How is it resolved using virtual base class? [5]

When a class inherits from two or more base classes that themselves share a common base class, the derived class ends up with multiple copies of the common base class members. This creates ambiguity because the compiler cannot determine which copy to use. This situation is commonly called the "Di...

Open this answer on its own page →

0 · 5 marks

What is meant by ambiguity? Explain ambiguity in multiple inheritance and its solution with example. [5]

Ambiguity refers to a situation in object-oriented programming where the compiler is unable to determine which version of a function or member to use when the same name exists in more than one base class or path. It creates confusion during compilation and results in a compile-time error if not r...

Open this answer on its own page →

Inheritance definition and purpose

2081 · 10 marks

List any two types of inheritance with example.Describe the order of execution of constructors and destructors in derived class.[5+5]

--- (a) Two Types of Inheritance with Examples When a derived class inherits from only one base class, it is called single inheritance. Syntax: Example: Diagram: --- When a derived class inherits from more than one base class, it is called multiple inheritance. Syntax: Example: Diagram: --- (b) O...

Open this answer on its own page →

Public, private, and protected inheritance

2080 · 5 marks

What is the difference between public, private and protected inheritance in C++? [5]

In C++, when a derived class inherits from a base class, an access specifier is used to control how the inherited members are accessible in the derived class and further down the hierarchy. Syntax: --- The inherited member's accessibility in the derived class is determined by the most restrictive...

Open this answer on its own page →

2080.1 · 5 marks

What is the role of protected access specifiers in inheritance? Explain with example. [5]

Show solved answer

Role of Protected Access Specifier in Inheritance

Definition

The protected access specifier is an access control modifier that makes class members accessible:

  • Within the same class
  • Within derived (child) classes
  • NOT accessible from outside the class hierarchy (unlike public)

It sits between private and public in terms of accessibility.

Access Specifier Comparison Table

Access SpecifierSame ClassDerived ClassOutside Class
privateYesNoNo
protectedYesYesNo
publicYesYesYes

Role in Inheritance

The key role of protected in inheritance is:

  • It allows base class members to be inherited and used by derived classes directly.
  • If a member is private, the derived class cannot access it directly, even though it inherits it.
  • protected solves this by giving derived classes direct access while still hiding the member from external code.

Example in C++

#include <iostream>
using namespace std;

class Animal {
private:
    int age;          // NOT accessible in derived class

protected:
    string name;      // Accessible in derived class, NOT outside

public:
    Animal(string n, int a) {
        name = n;
        age = a;
    }
};

class Dog : public Animal {
public:
    Dog(string n, int a) : Animal(n, a) {}

    void display() {
        // Accessing protected member 'name' from base class - ALLOWED
        cout << "Dog's name: " << name << endl;

        // Accessing private member 'age' - NOT ALLOWED (compile error)
        // cout << age << endl;  // Error!
    }
};

int main() {
    Dog d("Bruno", 3);
    d.display();

    // Accessing protected member from outside - NOT ALLOWED
    // cout << d.name;  // Error!

    return 0;
}

Output:

Dog's name: Bruno

Key Points

  1. protected members act like private to the outside world.
  2. protected members act like public to the derived classes.
  3. It enables data hiding while still supporting code reuse through inheritance.
  4. It is especially useful when a base class wants to share internal data with its subclasses without exposing it publicly.
Open this answer on its own page →

Aggregation versus inheritance

2079 · 5 marks

Differentiate between aggregation and inheritance. Why do we need virtual base class? [5]

--- Feature Aggregation Inheritance --------- Relationship "Has-a" relationship "Is-a" relationship Nature One class contains an object of another class as a member One class derives properties and behaviors from another class Code Reuse Achieved by using objects of existing classes Achieved by e...

Open this answer on its own page →

Single-level inheritance

2078 · 10 marks

Create a class Employee with private data members Eid, Ename, and Salary. Include public member functions read and display value of data members. Derive a class names typist from above class. The class should contain a private data members. Finally create two objects of typist class and read and display their values.[10]

Show solved answer

Class Employee with Derived Class Typist in C++

Concept Overview

This problem demonstrates Inheritance in Object-Oriented Programming (OOP):

  • Base Class: Employee (with private members: Eid, Ename, Salary)
  • Derived Class: Typist (inherits from Employee, adds its own private member)
  • Two objects of Typist are created, and values are read and displayed.

Complete C++ Program

#include <iostream>
#include <string>
using namespace std;

// Base Class: Employee
class Employee {
private:
    int Eid;
    string Ename;
    float Salary;

public:
    // Member function to read data
    void read() {
        cout << "Enter Employee ID: ";
        cin >> Eid;
        cout << "Enter Employee Name: ";
        cin >> Ename;
        cout << "Enter Salary: ";
        cin >> Salary;
    }

    // Member function to display data
    void display() {
        cout << "Employee ID   : " << Eid << endl;
        cout << "Employee Name : " << Ename << endl;
        cout << "Salary        : " << Salary << endl;
    }
};

// Derived Class: Typist (inherits from Employee)
class Typist : public Employee {
private:
    int typingSpeed;   // words per minute (private data member of Typist)

public:
    // Member function to read data (calls base class read)
    void read() {
        Employee::read();   // call base class read()
        cout << "Enter Typing Speed (words/min): ";
        cin >> typingSpeed;
    }

    // Member function to display data (calls base class display)
    void display() {
        Employee::display();   // call base class display()
        cout << "Typing Speed  : " << typingSpeed << " words/min" << endl;
    }
};

// Main Function
int main() {
    Typist t1, t2;   // Two objects of Typist class

    // Reading values for first object
    cout << "\n--- Enter details for Typist 1 ---" << endl;
    t1.read();

    // Reading values for second object
    cout << "\n--- Enter details for Typist 2 ---" << endl;
    t2.read();

    // Displaying values for first object
    cout << "\n--- Details of Typist 1 ---" << endl;
    t1.display();

    // Displaying values for second object
    cout << "\n--- Details of Typist 2 ---" << endl;
    t2.display();

    return 0;
}

Sample Output

--- Enter details for Typist 1 ---
Enter Employee ID: 101
Enter Employee Name: Ram
Enter Salary: 25000
Enter Typing Speed (words/min): 60

--- Enter details for Typist 2 ---
Enter Employee ID: 102
Enter Employee Name: Sita
Enter Salary: 22000
Enter Typing Speed (words/min): 75

--- Details of Typist 1 ---
Employee ID   : 101
Employee Name : Ram
Salary        : 25000
Typing Speed  : 60 words/min

--- Details of Typist 2 ---
Employee ID   : 102
Employee Name : Sita
Salary        : 22000
Typing Speed  : 75 words/min

Key Points to Remember

FeatureDescription
private membersEid, Ename, Salary in Employee; typingSpeed in Typist
public inheritanceclass Typist : public Employee
Employee::read()Scope resolution used to call base class function from derived class
Two objectst1 and t2 are objects of Typist class
EncapsulationPrivate data accessed only through public member functions

Note: Since Eid, Ename, and Salary are private in Employee, they cannot be accessed directly in Typist. They are accessed through the public member functions read() and display() of the base class using Employee::read() and Employee::display().

Open this answer on its own page →

0 · 10 marks

Create a class Employee with private data members Eid, Ename, and Salary. Include public member functions to read and display value of data members. Derive a class names Typist from above class. The class should contain a private data member typing_speed and public member functions to read and display values of data members. Finally create two objects of typist class and read and display their values.[10]

Show solved answer

Class Employee with Derived Class Typist in C++

Concept Overview

This problem demonstrates single inheritance in C++, where:

  • Employee is the base class (parent)
  • Typist is the derived class (child) that inherits from Employee
  • Private members of base class are accessed through public member functions

Complete C++ Program

#include <iostream>
#include <string>
using namespace std;

// Base Class: Employee
class Employee {
private:
    int Eid;
    string Ename;
    float Salary;

public:
    // Member function to read Employee data
    void readEmployee() {
        cout << "Enter Employee ID: ";
        cin >> Eid;
        cout << "Enter Employee Name: ";
        cin >> Ename;
        cout << "Enter Salary: ";
        cin >> Salary;
    }

    // Member function to display Employee data
    void displayEmployee() {
        cout << "Employee ID    : " << Eid << endl;
        cout << "Employee Name  : " << Ename << endl;
        cout << "Salary         : " << Salary << endl;
    }
};

// Derived Class: Typist (inherits from Employee)
class Typist : public Employee {
private:
    int typing_speed;  // words per minute

public:
    // Member function to read Typist data
    void readTypist() {
        readEmployee();  // call base class read function
        cout << "Enter Typing Speed (words/min): ";
        cin >> typing_speed;
    }

    // Member function to display Typist data
    void displayTypist() {
        displayEmployee();  // call base class display function
        cout << "Typing Speed   : " << typing_speed << " words/min" << endl;
    }
};

// Main Function
int main() {
    Typist t1, t2;  // Two objects of Typist class

    // Reading data for first typist
    cout << "\n--- Enter details for Typist 1 ---" << endl;
    t1.readTypist();

    // Reading data for second typist
    cout << "\n--- Enter details for Typist 2 ---" << endl;
    t2.readTypist();

    // Displaying data for first typist
    cout << "\n--- Details of Typist 1 ---" << endl;
    t1.displayTypist();

    // Displaying data for second typist
    cout << "\n--- Details of Typist 2 ---" << endl;
    t2.displayTypist();

    return 0;
}

Sample Output

--- Enter details for Typist 1 ---
Enter Employee ID: 101
Enter Employee Name: Ram
Enter Salary: 25000
Enter Typing Speed (words/min): 60

--- Enter details for Typist 2 ---
Enter Employee ID: 102
Enter Employee Name: Sita
Enter Salary: 22000
Enter Typing Speed (words/min): 75

--- Details of Typist 1 ---
Employee ID    : 101
Employee Name  : Ram
Salary         : 25000
Typing Speed   : 60 words/min

--- Details of Typist 2 ---
Employee ID    : 102
Employee Name  : Sita
Salary         : 22000
Typing Speed   : 75 words/min

Key Points to Remember

FeatureDescription
Private membersEid, Ename, Salary, typing_speed cannot be accessed directly outside their class
Public inheritanceclass Typist : public Employee means public members of Employee remain public in Typist
ReusabilityreadEmployee() and displayEmployee() are reused inside Typist methods
Two objectst1 and t2 are two separate objects of Typist class
EncapsulationData is hidden (private) and accessed only through public functions

Note: Since Eid, Ename, and Salary are private in Employee, the derived class Typist cannot access them directly. They are accessed indirectly through the public member functions readEmployee() and displayEmployee().

Open this answer on its own page →