WEEK 15 · LAB 6
Lab 6 — Class Inheritance
Extend a Person class with a student's score.
Objectives Environment Tasks Submission
I. Objectives
Recognize a base class and a derived class that uses public inheritance.
Reuse a base class member function in a derived class.
Before the Lab Week 14: 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
A computer with Windows, macOS, or Linux.
Use OnlineGDB in C++ mode, or the C++ environment demonstrated in class.
Save your program as lab06.cpp. Use one source file for this lab.
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.
#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 92IV. Lab Report Submission Submit one lab report for this lab, in English or Chinese. Include the following content in the report.
Student information: name, student ID, class, lab number, and lab title.
Objectives and environment: briefly describe the lab objectives and the C++ environment you used.
Procedure and code: explain how you completed the tasks and include the complete code from lab06.cpp in the report.
Tests and results: record the test inputs and results, include one or two screenshots, and explain whether the results match the expected output.
Answers and reflection: answer the two questions below and briefly describe what you learned or a problem you solved.
Questions for the Report
Which class stores the name, and which class stores the score?
Which part of the program shows that Student inherits Person?
← Back to Schedule Previous Lab