C++: A student is a person

Reuse a class by building a new one on top of it.

What to build

A Student class derived from Person, which adds an ID.

Requirements

  • Person keeps the name and has introduce(), which prints I am NAME.
  • Student derives publicly from Person, adds an ID and has showId(), which prints My ID is ID.
  • For each student, call both functions on the same Student object.

Input

The first line has q. Each of the next q lines has a name and an ID.

Output

Two lines per student.

Constraints

1 ≤ q ≤ 100, names are one word, and IDs are from 0 to 1000000.

Example

Input:

2
Asha 101
Bilal 202

Output:

I am Asha
My ID is 101
I am Bilal
My ID is 202

Why it works

A Student contains a Person part, so it can call introduce() without any new code. Only what is new, the ID, is written in Student.

Examples

Example 1 · Input
2
Asha 101
Bilal 202
Expected output
I am Asha
My ID is 101
I am Bilal
My ID is 202
Example 2 · Input
1
X 0
Expected output
I am X
My ID is 0

Hints

Hint 1

`class Student : public Person` gives every Student the Person part.

Hint 2

The Student constructor passes the name on: `Student(string n, int i) : Person(n), id(i) {}`.

Solution

Show one correct solution (try it yourself first)
#include <iostream>
#include <string>
using namespace std;

class Person {
protected:
    string name;
public:
    Person(string n) : name(n) {}
    void introduce() const {
        cout << "I am " << name << endl;
    }
};

class Student : public Person {
    int id;
public:
    Student(string n, int i) : Person(n), id(i) {}
    void showId() const {
        cout << "My ID is " << id << endl;
    }
};

int main() {
    int q;
    cin >> q;
    while (q-- > 0) {
        string name;
        int id;
        cin >> name >> id;
        Student s(name, id);
        s.introduce();
        s.showId();
    }
    return 0;
}

Lesson: Inheritance →