Skip to main content

Protected specifier; student/test/result program

Short answer

A protected member is accessible within its class and derived classes, hidden from outside. A multilevel program: Student holds roll/name, Test adds three subject marks, Result computes total and percentage, and displays pass/fail if all marks ≥40.

What is a protected access specifier? Write a program with three classes students, test and result by using multilevel inheritance. Assume necessary data members and functions yourself and program with input information, input data and calculate marks total and display result.

Protected access specifier

A member declared protected is accessible within its own class and in classes derived from it, but not from outside code (e.g. main()). It lies between private (only the class) and public (everyone). It lets derived classes use base data while still hiding it from the outside.

Program: multilevel inheritance Student -> Test -> Result

  • Student stores roll number and name.
  • Test (derived from Student) stores marks in three subjects.
  • Result (derived from Test) calculates total and percentage and displays the result.
#include <iostream>
#include <string>
using namespace std;

class Student {
protected:
    int roll;
    string name;
public:
    void getInfo() {
        cout << "Enter roll number and name: ";
        cin >> roll >> name;
    }
};

class Test : public Student {
protected:
    float m1, m2, m3;
public:
    void getMarks() {
        cout << "Enter marks in 3 subjects: ";
        cin >> m1 >> m2 >> m3;
    }
};

class Result : public Test {
    float total, percent;
public:
    void calculate() {
        total = m1 + m2 + m3;
        percent = total / 3;
    }
    void display() {
        cout << "\nRoll: " << roll << "  Name: " << name << endl;
        cout << "Marks: " << m1 << ", " << m2 << ", " << m3 << endl;
        cout << "Total = " << total << ", Percentage = " << percent << "%" << endl;
        if (m1 >= 40 && m2 >= 40 && m3 >= 40)
            cout << "Result: Pass" << endl;
        else
            cout << "Result: Fail" << endl;
    }
};

int main() {
    Result r;
    r.getInfo();
    r.getMarks();
    r.calculate();
    r.display();
    return 0;
}

Sample run:

Enter roll number and name: 7 Sita
Enter marks in 3 subjects: 78 65 82

Roll: 7  Name: Sita
Marks: 78, 65, 82
Total = 225, Percentage = 75%
Result: Pass

Result reads roll, name, m1, m2 and m3 directly because they are protected in their parent classes.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 6 questions →