5 Inheritance

Object Oriented Programming ยท Unit 5 ยท 7 hrs

Inheritance

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

Inheritance in short

This unit covers how one class derives from another to reuse and extend its features: the base and derived class relationship, how access specifiers control what a derived class inherits, the five types of inheritance and how public versus private derivation changes visibility, how constructors and destructors run in an inheritance chain, and aggregation, the alternative relationship where one class simply contains objects of another.

Inheritance: notes

Introduction to inheritance

Inheritance is the mechanism by which a new class acquires the properties, both data and behaviour, of an existing class, so that features already defined for one class do not have to be rewritten for a related class; a Robin class can inherit everything already defined in a FlyingBird class, which itself inherits from Bird. This is what gives object oriented programs reusability: additional, more specific features can be added to a new class without touching the class it is built on.

Derived Class and Base Class

The existing class from which properties are inherited is called the base class (or parent class), and the new class that inherits some or all of those properties is called the derived class (or child class). A derived class is declared by naming its base class and the visibility (access) mode under which it is inherited:

class DerivedClassName : visibility_mode BaseClassName {
    // additional data members and member functions of the derived class
};

Access Specifiers (private, protected, and public)

Within a single class, private members are visible only to the class's own member functions, protected members are visible to the class's own member functions and to any class derived from it, and public members are visible everywhere the object itself is visible. In an inheritance relationship, the visibility mode used at the point of derivation additionally decides how the base class's members appear inside the derived class:

Base class memberPublic derivationPrivate derivationProtected derivation
publicbecomes public in derived classbecomes private in derived classbecomes protected in derived class
protectedstays protectedbecomes privatestays protected
privatenot inherited (inaccessible)not inherited (inaccessible)not inherited (inaccessible)

A base class's private members are never directly accessible in a derived class no matter what visibility mode is used for the derivation; they can only be reached indirectly, through the base class's own public or protected member functions.

What this unit covers

  • Introduction to inheritance
  • Derived Class and Base Class
  • Access Specifiers (private, protected, and public)
  • Types of inheritance
  • Public and Private Inheritance
  • Constructor and Destructor in derived classes
  • Aggregation

Types of inheritance

2080 ยท 10 marks

State the use of new operator. An educational institute wishes to maintain a data of its employee. The hierarchical relationships of related classes are as follows. Define all the classes to represent above hierarchy and define functions to retrieve individual information as and when required.[10]

Show solved answer

New Operator and Employee Hierarchy in C++

Use of new Operator (2 marks)

The new operator in C++ is used for dynamic memory allocation. It allocates memory at runtime from the heap (free store) and returns a pointer to the beginning of the allocated memory block.

Key uses:

  • Allocates memory for a variable or object during program execution
  • Returns a pointer to the allocated memory
  • Memory persists until explicitly released using delete
  • Syntax: pointer_variable = new data_type;

Example:

int *ptr = new int;        // allocates memory for one integer
int *arr = new int[10];    // allocates memory for array of 10 integers
delete ptr;                // free single variable
delete[] arr;              // free array

Employee Hierarchy Program (8 marks)

Class Hierarchy Structure

           Employee
          (name, emp_id)
               |
        ________________
        |               |
    Teacher          Officer
  (subject,        (department,
   salary)           salary)
        |
   Typist
  (speed,
   salary)

Complete C++ Program

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

// โ”€โ”€โ”€ Base Class โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
class Employee {
protected:
    string name;
    int emp_id;

public:
    // Function to set employee data
    void getEmployeeData() {
        cout << "Enter Employee Name: ";
        cin >> name;
        cout << "Enter Employee ID: ";
        cin >> emp_id;
    }

    // Function to display employee data
    void showEmployeeData() {
        cout << "\n--- Employee Information ---" << endl;
        cout << "Name     : " << name << endl;
        cout << "Emp ID   : " << emp_id << endl;
    }
};

// โ”€โ”€โ”€ Derived Class: Teacher โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
class Teacher : public Employee {
protected:
    string subject;
    float salary;

public:
    // Function to set teacher data
    void getTeacherData() {
        getEmployeeData();   // call base class function
        cout << "Enter Subject Specialization: ";
        cin >> subject;
        cout << "Enter Salary: ";
        cin >> salary;
    }

    // Function to display teacher data
    void showTeacherData() {
        showEmployeeData();  // call base class function
        cout << "Subject  : " << subject << endl;
        cout << "Salary   : " << salary << endl;
    }
};

// โ”€โ”€โ”€ Derived Class: Typist (derived from Teacher) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
class Typist : public Teacher {
private:
    int typingSpeed;   // words per minute

public:
    // Function to set typist data
    void getTypistData() {
        getTeacherData();
        cout << "Enter Typing Speed (wpm): ";
        cin >> typingSpeed;
    }

    // Function to display typist data
    void showTypistData() {
        showTeacherData();
        cout << "Typing Speed: " << typingSpeed << " wpm" << endl;
    }
};

// โ”€โ”€โ”€ Derived Class: Officer โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
class Officer : public Employee {
private:
    string department;
    float salary;

public:
    // Function to set officer data
    void getOfficerData() {
        getEmployeeData();   // call base class function
        cout << "Enter Department: ";
        cin >> department;
        cout << "Enter Salary: ";
        cin >> salary;
    }

    // Function to display officer data
    void showOfficerData() {
        showEmployeeData();  // call base class function
        cout << "Department: " << department << endl;
        cout << "Salary    : " << salary << endl;
    }
};

// โ”€โ”€โ”€ Main Function โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
int main() {
    int choice;
    cout << "===== Educational Institute Employee System =====" << endl;
    cout << "1. Teacher\n2. Typist\n3. Officer" << endl;
    cout << "Enter your choice: ";
    cin >> choice;

    // Using new operator for dynamic object creation
    if (choice == 1) {
        Teacher *t = new Teacher;
        t->getTeacherData();
        t->showTeacherData();
        delete t;
    }
    else if (choice == 2) {
        Typist *ty = new Typist;
        ty->getTypistData();
        ty->showTypistData();
        delete ty;
    }
    else if (choice == 3) {
        Officer *o = new Officer;
        o->getOfficerData();
        o->showOfficerData();
        delete o;
    }
    else {
        cout << "Invalid choice!" << endl;
    }

    return 0;
}

Sample Output

===== Educational Institute Employee System =====
1. Teacher
2. Typist
3. Officer
Enter your choice: 1

Enter Employee Name: Ram
Enter Employee ID: 101
Enter Subject Specialization: Mathematics
Enter Salary: 45000

--- Employee Information ---
Name     : Ram
Emp ID   : 101
Subject  : Mathematics
Salary   : 45000

Key Concepts Used

ConceptApplication
Base ClassEmployee holds common data (name, emp_id)
InheritanceTeacher, Officer inherit from Employee; Typist inherits from Teacher
protected membersAllow derived classes to access base class data directly
new operatorUsed to create objects dynamically at runtime
Function overridingEach derived class defines its own show and get functions
public inheritanceDerived class inherits all public and protected members of base class

**

Open this answer on its own page โ†’

2078 ยท 10 marks

How ambiguity arises in multipath inheritance? How can you remove this type of ambiguity? Explain with suitable example.[10]

Multipath inheritance (also called diamond problem or hybrid inheritance) occurs when a derived class inherits from two or more base classes that themselves share a common ancestor. This creates multiple paths through which the derived class can access the members of the topmost base class, leadi...

Open this answer on its own page โ†’

2076 ยท 10 marks

Write a program according to the specification given below:- Create a class Teacher with data members id & subject and member functions for reading and displaying data members.- Create another class Staff with data members id & position, and member functions for reading and displaying data members.- Derive a class Coordinator from Teacher and Staff and the class must have its own data member department and member functions for reading and displaying data members.- Create two object of Coordinator class and read and display their details.[10]

This program demonstrates multiple inheritance in C++, where a derived class Coordinator inherits from two base classes Teacher and Staff. The derived class has its own data member department along with inherited members from both base classes. --- --- --- --- Feature Description ------ Multiple ...

Open this answer on its own page โ†’

2075 ยท 5 marks

Briefly explain types of inheritance used in object oriented programming. [5]

Inheritance is one of the key features of Object Oriented Programming that allows a new class (derived/child class) to acquire the properties and behaviors of an existing class (base/parent class)., "through inheritance, we can eliminate redundant code and extend the use of existing classes." ---...

Open this answer on its own page โ†’

Constructor and Destructor in derived classes

2080 ยท 5 marks

Describe the chain of constructors and destructors in inheritance. [5]

In inheritance, when an object of a derived class is created or destroyed, constructors and destructors of both the base class and the derived class are automatically invoked in a specific order. --- When a derived class object is created, constructors are called in top-down order, i.e., from the...

Open this answer on its own page โ†’

Aggregation

2079 ยท 10 marks

What is aggregation? Write a program for implementing following: Create a class author with attributes name and qualification. Also create a class publication with name. Form these classes to derive a class book having attribute title and price. Each of three classes should have a getdata() method to get their data from user. The classes should have putdata() method to display the data. Create instances of the class book in main.[10]

Aggregation is a special form of association in Object-Oriented Programming where one class contains objects of other classes as its members, but the contained objects can exist independently of the container class. It represents a "has-a" relationship between classes. - In aggregation, the conta...

Open this answer on its own page โ†’

Access Specifiers

2079 ยท 5 marks

What are the various class access specifies? How public inheritance differs from private inheritance? [5]

Show solved answer

Class Access Specifiers and Public vs Private Inheritance

Access Specifiers in C++

A class uses access specifiers to control the visibility of its data members and member functions. There are three access specifiers in C++:


1. Private

  • Members declared as private are visible only to member functions of their own class.
  • They cannot be accessed from outside the class or by derived classes directly.
  • If no access specifier is mentioned, members are private by default.
class Example {
    int x;  // private by default
private:
    int y;  // explicitly private
};

2. Protected

  • Members declared as protected are visible to member functions of their own class and derived classes.
  • They cannot be accessed from outside these classes (data hiding is maintained).
  • Useful when inheritance is involved.
class Example {
protected:
    int x;  // accessible in derived class
};

3. Public

  • Members declared as public are visible to all functions in the program.
  • They can be accessed from anywhere using the dot operator (.) with an object.
class Example {
public:
    int x;  // accessible from anywhere
};

Summary Table

Access SpecifierOwn ClassDerived ClassOutside Class
privateYesNoNo
protectedYesYesNo
publicYesYesYes

Public Inheritance vs Private Inheritance

When a derived class inherits from a base class, the mode of inheritance determines how the base class members are accessible in the derived class.


Public Inheritance

class Derived : public Base {
    // ...
};
  • public members of Base remain public in Derived.
  • protected members of Base remain protected in Derived.
  • private members of Base are not accessible in Derived.
  • Objects of the derived class can access the public members of the base class.
  • This represents an "is-a" relationship.

Private Inheritance

class Derived : private Base {
    // ...
};
  • public members of Base become private in Derived.
  • protected members of Base become private in Derived.
  • private members of Base are not accessible in Derived.
  • Objects of the derived class cannot access any inherited members from outside.
  • This represents a "has-a" (implementation) relationship.

Comparison Table

FeaturePublic InheritancePrivate Inheritance
Base public membersRemain public in DerivedBecome private in Derived
Base protected membersRemain protected in DerivedBecome private in Derived
Base private membersNot accessibleNot accessible
Access via objectAllowedNot allowed
Relationship"is-a""has-a"

Example

class Base {
public:
    int x;
protected:
    int y;
private:
    int z;
};

class PublicDerived : public Base {
    // x is public, y is protected, z is not accessible
};

class PrivateDerived : private Base {
    // x is private, y is private, z is not accessible
};

int main() {
    PublicDerived pd;
    pd.x = 10;   // Allowed (x is public)

    PrivateDerived pvd;
    pvd.x = 10;  // ERROR: x is private in PrivateDerived
}

Key Point: Public inheritance preserves the access levels of base class members, while private inheritance makes all inherited members private, restricting access from outside the derived class.

Open this answer on its own page โ†’

2080.1 ยท 5 marks

Explain the practical implication of protected specifier in inheritance. List advantages and disadvantages of inheritance. [5]

"Protected access specifier is similar to that of private access specifiers, the difference is that the class member declared as protected are inaccessible outside the class but they can be accessed by any subclass (derived class) of that class." The protected specifier plays a crucial role speci...

Open this answer on its own page โ†’

Public and Private Inheritance

2075 ยท 10 marks

Depict the difference between private and public derivation. Explain derived class constructor with suitable program.[10]

--- When a derived class inherits from a base class, the visibility of inherited members in the derived class depends on the type of derivation used. Feature Public Derivation Private Derivation --------- Base class public members Remain public in derived class Become private in derived class Bas...

Open this answer on its own page โ†’