C++ Programming

WEEK 14 · LAB 6

Lab 6 — Polymorphic Public Inheritance

Use one function to introduce a student and a teacher.

I. Objectives

Before the Lab

Weeks 7, 9, and 13: references, const member functions, virtual functions, and override. const Person& refers to the original object without copying it. Review the supplied virtual destructor before running the code; keep that line as provided.

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 the common interface

  • Person provides virtual introduce(). Student and Teacher each override it. showIntroduction() accepts a Person reference and calls introduce(). Keep this supplied structure.

Task 2 — Complete the two introductions

  • At TODO 1, print I am a student. At TODO 2, print I am a teacher. End each line with a newline. Keep const and override in the function declarations.

Task 3 — Observe and explain the two calls

  • Run main() and compare the two output lines. Then swap the two calls to showIntroduction() and run again; the output order should also swap. No pointers or dynamic allocation are needed.

Starter Code

Download .cpp
#include <iostream>

class Person {
public:
    virtual void introduce() const {
        std::cout << "I am a person." << '\n';
    }

    virtual ~Person() = default;
};

class Student : public Person {
public:
    void introduce() const override {
        // TODO 1: Print the student's introduction.
    }
};

class Teacher : public Person {
public:
    void introduce() const override {
        // TODO 2: Print the teacher's introduction.
    }
};

void showIntroduction(const Person& person) {
    person.introduce();
}

int main() {
    Student student;
    Teacher teacher;
    showIntroduction(student);
    showIntroduction(teacher);
    return 0;
}

Expected Output

Expected output after completing both introductions.

I am a student.
I am a teacher.

IV. Submission

Two Short Questions

  1. Why does the same showIntroduction() function produce two different messages?
  2. Which class's introduce() runs when the argument is teacher?