C++ Programming

WEEK 10 · LAB 4

Lab 4 — Objects and Classes

Create two student objects and display their information.

I. Objectives

Before the Lab

Week 9: std::string, public and private members, constructors, and const member functions. A constructor sets up an object; show() const displays its data without changing its data members.

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 Student class

  • Find the private data members name and score. Find the constructor and show(). Run the starter; it will not display student information until the TODOs are completed.

Task 2 — Complete the constructor and show()

  • At TODO 1, assign studentName to name and studentScore to score. At TODO 2, print the name and score on one line, as shown below.

Task 3 — Test two independent objects

  • Run the program for Alex (85) and Sam (92). Then change only Sam's score to 70 and run it again. Alex's score should still be 85.

Starter Code

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

class Student {
private:
    std::string name;
    int score = 0;

public:
    Student(std::string studentName, int studentScore) {
        // TODO 1: Set name and score.
    }

    void show() const {
        // TODO 2: Print name and score.
    }
};

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

Expected Output

Expected output after completing both TODOs.

Alex 85
Sam 92

IV. Submission

Two Short Questions

  1. When is the Student constructor called?
  2. Why can first and second store different scores?