Create a base class `Person` with members `name` and `age`. Derive a class `Student` with an additional member `percentage`. Accept and display data using constructor and member functions.

SOLUTION....


#include <iostream>
using namespace std;

// Base class
class Person {
protected:
    string name;
    int age;

public:
    // Constructor
    Person(string n, int a) {
        name = n;
        age = a;
    }

    // Display function
    void displayPerson() {
        cout << "Name: " << name << endl;
        cout << "Age: " << age << endl;
    }
};

// Derived class
class Student : public Person {
private:
    float percentage;

public:
    // Constructor (calls base class constructor using initializer list)
    Student(string n, int a, float p) : Person(n, a) {
        percentage = p;
    }

    // Display function
    void displayStudent() {
        displayPerson();
        cout << "Percentage: " << percentage << "%" << endl;
    }
};

// Main function
int main() {
    string n;
    int a;
    float p;

    cout << "Enter Name: ";
    getline(cin, n);
    cout << "Enter Age: ";
    cin >> a;
    cout << "Enter Percentage: ";
    cin >> p;

    // Create object of Student
    Student s(n, a, p);

    cout << "\n--- Student Details ---\n";
    s.displayStudent();

    return 0;
}

OUTPUT

Leave a Reply

Your email address will not be published. Required fields are marked *