C++ Programming

WEEK 12 · LAB 5

Lab 5 — Class Inheritance

Extend a Person class with a student's score.

I. Objectives

Before the Lab

Week 11: base and derived classes, public inheritance, and member initialization lists. In : Person(studentName), score(studentScore), the base-class part is initialized before the derived data member. Both constructors are supplied.

II. Environment

Open OnlineGDB ↗

III. Tasks and Requirements

Complete the TODOs in the starter code, then compare your result with the expected output. The starter is intentionally unfinished.

Task 1 — Read Person and Student

  • Person stores a name and provides getName(). Student publicly inherits Person and adds a score. Their constructors are provided.

Task 2 — Complete Student::show()

  • At TODO 1, call getName() and print the returned name followed by a space and score. The base-class name is private, so use getName() to read it.

Task 3 — Test the derived objects

  • Run the program for Alex (85) and Sam (92). Change only Sam's score to 70, then run again. Check that both names remain correct.

Starter Code

Download .cpp
#include <iostream>
#include <string>

class Person {
private:
    std::string name;

public:
    Person(std::string personName) : name(personName) {}

    std::string getName() const {
        return name;
    }
};

class Student : public Person {
private:
    int score;

public:
    Student(std::string studentName, int studentScore)
        : Person(studentName), score(studentScore) {}

    void show() const {
        // TODO 1: Print the inherited name and this student's score.
    }
};

int main() {
    Student first("Alex", 85);
    Student second("Sam", 92);
    first.show();
    second.show();
    return 0;
}

Expected Output

Expected output for the original scores.

Alex 85
Sam 92

IV. Submission

Two Short Questions

  1. Which class stores the name, and which class stores the score?
  2. Which part of the program shows that Student inherits Person?