[CS200.U07.EX] Exercise: Classes and OOP

CS 200: Concepts of Programming with C++, Summer 2022

🔙 BACK TO UNIT PAGE | CANVAS TURN IN


📝 Assignment

Exercises are meant to be solo effort, please try to complete it on your own. You can ask the instructor or a tutor questions if you get really stuck, but all the information you need to complete the assignment is in here, or in the related reading/lectures.

If you get stuck, please post questions in the Unit 7 'Help!' discussion board.

🔧 Setup

FIRST, from your "My Repls" page on Repl.it create a New folder for this weeks' assignments name it Unit07. Within this folder you will create separate Repl projects for each program. When you turn in the assignments, you will copy the URL to your folder as the submission.

🎁 Submitting your work

First, make sure all your programs are inside your Unit07 folder. If they're not you can click on the three dots on the right side of the program name and click "Move".

PLEASE GIVE YOUR PROGRAMS THE FOLLOWING NAMES:

  • Unit 07 Program 1
  • Unit 07 Program 2
  • Unit 07 Program 3
  • Unit 07 Program 4
  • Unit 07 Program 5

Clean code also means the ability to find the code itself, so if your project is unkempt and hard to navigate you will lose points.

To submit your work, navigate to the folder for your exercises on replit. Copy the URL to that directory (e.g., https://replit.com/@rsingh13?path=folder/Unit07) and paste it in here in Canvas.

Once you've turned in the assignment, make sure to also post your program in the code review assignment, [CS200.U07.PR] 🔎 Classes and Inheritance - Peer review

💻 Programs

Quick jump: Program 1: RPG Dice | Program 2: Quiz v1 | Program 3: Quiz v2 | Program 4: Courses | Program 5: Basic inheritance

Program 1: RPG Dice

When playing tabletop games, players usually have several sets of dice with different amount of sides.

How many sides should the die have? 20
How many times do you want to roll the die? 6
Roll #1: 10
Roll #2: 7
Roll #3: 1
Roll #4: 3
Roll #5: 6
Roll #6: 15

Files needed

You will need a main.cpp file for main() and a Die.h file for the class declaration and a Die.cpp for the function definitions.


Using random numbers

Since we are going to use random numbers, make sure to include the following in your Die.cpp file:

#include <cstdlib>

And in your main.cpp include:

#include <cstdlib>
#include <ctime>
We will also need to SEED the random number generator at the beginning of main(), like this:
srand( time( NULL ) );


Class creation

We are going to create a simple class with the following requirements. Remember that class and function declarations go in the Die.h file and function definitions go in the Die.cpp file.

UML Notes:

  • Items marked with - are private
  • Items marked with + are public
  • Variables are written in the form NAME : DATATYPE, so in code it would be DATATYPE NAME;
  • Functions are written in the form NAME( PARAM : TYPE, PARAM : TYPE ) : RETURNTYPE, so in code it would be RETURNTYPE NAME( TYPE PARAM, TYPE PARAM )
Die
- m_sides : int
+ SetSides( sides : int ) : void
+ RollDie() : int


Function Name

void Die::SetSides( int sides );

Inputs

sides, an int

Returns

void

Within this function, set the value of m_sides to the value passed in as the sides parameter.

Function Name

int Die::RollDie()

Inputs

None

Returns

int

Within this function we're going to call the random number function, using 1 as the minimum and sides as the maximum. To get a random number in this range, we have to use this:
return rand() % ( max - min + 1 ) + min;
(Yes, it's ugly, but this is why writing a nice "Get Random" function would be useful ;)
Your min will be 1, and the max will be whatever the amount of sides is.



Remember that your class declaration and function declarations go in the Die.h file and the function definitions go in the Die.cpp file.

Once you're finished with these steps, Die.h should look like this:

// DON'T FORGET THE FILE GUARDS!
#ifndef _DIE_H
#define _DIE_H

class Die
{
    public:
    int Roll();
    void SetSides( int sides );

    private:
    int m_sides;
}; // DON'T FORGET THE ; AT THE END!
#endif

And Die.cpp should look like this:

#include "Die.h"
#include <cstdlib>

int Die::Roll()
{
    int min = 1;
    int max = m_sides;
    return rand() % ( max - min + 1 ) + min;
}

void Die::SetSides( int sides )
{
    m_sides = sides;
}

Writing the program

Beneath all of that we will write the actual program. Do the following steps:

  1. Seed the random number generator:
    srand( time( NULL ) );
  2. Ask the user how many sides the die should have and store the result in a temporary variable:
    int sides = 0;
    cout << "How many sides should the die have? ";
    cin >> sides;
    
  3. Ask the user how many times they want the die to roll, and store it in a new variable named rolls:
    int rolls = 0;
    cout << "How many times do you want to roll the die? ";
    cin >> rolls;
    
  4. Create a new variable named myDie and initialize it as a Die class object:
    Die myDie;
  5. Set the die's amount of sides by calling its SetSides function:
     myDie.SetSides( sides );
  6. Use a for loop to iterate rolls times (for ( int i = 1; i <= rolls; i++ )). Within the for loop, do the following:
    1. Call the Die's Roll() function, storing the result in a new variable called result.
      int result = myDie.Roll();
    2. Display the result to the user:
      cout << "Roll #" << i << ": " << result << endl;

Once all of the code is done your program should look like this:

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

#include "Die.h"

int main()
{
    srand( time( NULL ) );

    int sides = 0;
    cout << "How many sides should the die have? ";
    cin >> sides;

    int rolls = 0;
    cout << "How many times do you want to roll the die? ";
    cin >> rolls;

    Die myDie;
    myDie.SetSides( sides );

    for ( int i = 1; i <= rolls; i++ )
    {
        int result = myDie.Roll();
        cout << "Roll #" << i << ": " << result << endl;
    }

    return 0;
}

And the program output will look like this:

How many sides should the die have? 20
How many times do you want to roll the die? 6
Roll #1: 10
Roll #2: 7
Roll #3: 1
Roll #4: 3
Roll #5: 6
Roll #6: 15

Program 2: Quiz v1

⭐⭐

For this program we will create a Question class that will ask the user a question, get their guess, and check if their result was correct or not.

What command do you use to display information in Python?
Your guess: print

CORRECT!

File setup

Create a project and create the following files: main.cpp, Question.h, and Question.cpp.


The Question class

Function Name

void Question::Setup( string question, string answer );

Inputs

question, a string
answer, a string

Returns

void

This function takes two inputs, question and answer. Assign the corresponding private member variable to each of these items.

Question
- m_question : string
- m_answer : string
+ Setup( question : string, answer : string ) : void
+ AskQuestion() : bool


Function Name

bool Question::AskQuestion();

Inputs

none

Returns

bool

Within the function, do the following:

  1. Print out the Question's text.
  2. Get the user's guess, storing it in a temporary string variable.
  3. Use an if/else statement to check if the guess matches the answer.
    If it matches, display "CORRECT!" and return true.
    If it doesn't match, display "INCORRECT!" and return false.

Once the class is done, Question.h should look like this:

#ifndef _QUESTION_H
#define _QUESTION_H

#include <string>
using namespace std;

class Question
{
    public:
    bool AskQuestion();
    void Setup( string question, string answer );

    private:
    string m_question;
    string m_answer;
};

#endif

Once the class is done, Question.cpp should look like this:

#include "Question.h"

#include <iostream>
using namespace std;


bool Question::AskQuestion()
{
    cout << m_question << endl << endl;

    string guess;
    cout << "Your guess: ";
    getline( cin, guess );

    cout << endl;

    if ( guess == m_answer )
    {
        cout << "CORRECT!" << endl;
        return true;
    }
    else
    {
        cout << "INCORRECT!" << endl;
        return false;
    }
}

void Question::Setup( string question, string answer )
{
    m_question = question;
    m_answer = answer;
}

Writing the program

Within main(), do the following:

  1. Create a Question object.
  2. Use the Question's Setup function to set up the question and answer text.
  3. Use the Question's AskQuestion function to ask the question when the program is run.

Even though the function returns true and false, we won't check on that result until v2 of the Quizzer, so for now it is fine that it just prints CORRECT! or INCORRECT!

Test out the program and make sure it looks like the example output.

Don't forget that in main.cpp you need to include the Question.h file! Never include .cpp files!

Program 2: Quiz v2

⭐⭐⭐

For v2 of the Quiz program, we will write a class for a Quiz, which contains a list of Questions within it.

QUESTION 1
            
What command do you use to display information in Python?

Your guess: print

CORRECT!


QUESTION 2

What command do you use to get information from the keyboard in Python?

Your guess: input

CORRECT!


QUESTION 3

What is the add operator in Python?

Your guess: *

INCORRECT!


QUESTION 4

How do you declare a variable named 'num' and assign it a value of 2?

Your guess: num = 2

CORRECT!


RESULTS
Score: 0.75%
            

Creating the project

Create a fork of the Quiz v1 program and rename this project Quiz v2. You will need to add a Quiz.h file and a Quiz.cpp file.

If you make a new project instead, make sure to copy over your Question.h and Question.cpp files.

Writing the Quiz class

Function Name

CreateQuestion

Inputs

index, an int
question, a string
answer, a string

Returns

void

This function is responsible for setting up questions in the m_questionList array at the index passed in. Call the Question's Setup function.

Quiz
- m_questionList : Question size [4]
+ CreateQuestion( index : int, question : string, answer : string ) : void
+ Run() : void


Function Name

Run()

Inputs

none

Returns

void

Within the function, do the following:

  1. Create a variable called totalRight and initialize it to 0.
  2. Use a for loop to iterate over all the questions in m_questionList. Within the for loop, do the following:
    1. Print "QUESTION" and then the counter (can put i+1 to make it more human-friendly.)
    2. The current question is accessed with m_questionList[i]. Call the current question's AskQuestion() function, storing its result in a new boolean variable called result.
    3. If the result is true, then add 1 to the totalRight variable.
  3. Once the for loop is over, calculate the score percent by dividing the totalRight by the length of the array (use 4.0, because if you divide two integers it will not have the remainder), then multiplying by 100.
  4. Print the results (the score) to the user.

The Quiz.h file will look like this:

#ifndef _QUIZ_H
#define _QUIZ_H

#include "Question.h"

class Quiz
{
    public:
    void CreateQuestion( int index, string question, string answer );
    void Run();

    private:
    Question m_questionList[4];
};

#endif

The Quiz.cpp file will look like this:

#include "Quiz.h"

#include <iostream>
using namespace std;

void Quiz::CreateQuestion( int index, string question, string answer )
{
    m_questionList[index].Setup( question, answer );
}

void Quiz::Run()
{
    int totalRight = 0;

    for ( int i = 0; i < 4; i++ )
    {
        cout << "QUESTION " << i << endl;
        bool result = m_questionList[i].AskQuestion();

        if ( result == true )
        {
            totalRight++;
        }

        cout << endl;
    }

    float scorePercent = totalRight / 4.0;

    cout << endl << "RESULTS" << endl;
    cout << "Score: " << scorePercent << "%" << endl;
}

Writing the program

Remove the old Question code from v1 of the quiz in main.cpp. This time, we're going to create a Quiz variable and use it to create all of our questions.

Create a Quiz object named quiz.

Call the CreateQuestion function several times to set up questions:

quiz.CreateQuestion( 0, "What command do you use to display information in Python?", "print" );
quiz.CreateQuestion( 1, "What command do you use to get information from the keyboard in Python?", "input" );
quiz.CreateQuestion( 2, "What is the add operator in Python?", "+" );
quiz.CreateQuestion( 3, "How do you declare a variable named 'num' and assign it a value of 2?", "num = 2" );

Once all the setup is done, call the Quiz's Run function to run the quiz when the program begins. The program output should look like the example above.

Program 4: Courses

⭐⭐⭐⭐

For this program you will be creating a class to store a Person's info and a Course's info. Similar to the Quiz, the Course will have a list of students.

COURSE NAME: CS134
COURSE CODE: Programming Fundamentals
INSTRUCTOR:  Rachel Singh (5944)
STUDENTS:
0. Ellene Largen (7184)
1. Sol Groucutt (4803)
2. Anton Caghan (6229)
3. Mei Drohane (4577)

Class - Person

The person class will be used to store information on students and the teacher of a course.

Function name

Setup

Inputs

id, an int
name, a string

Returns

void

Take the parameters and assign their values to the corresponding member variables.

Function name

Display

Inputs

None

Returns

void

Display the person's name and id to the screen.

Person
- m_id : int
- m_name : string
+ Setup( id : int, name : string ) : void
+ Display() : void

Class - Course

The Course class contains basic information about a course, including a list of students and the teacher.

Function name

Course constructor

Inputs

None

Returns

None

Initialize the m_studentCount to 0 here.

Function name

Setup

Inputs

name, string
code, string

Returns

void

This function takes the input parameters and assigns them to the corresponding private member variables.

Course
- m_name : string
- m_code : string
- m_teacher : Person
- m_students[20] : Person
- m_studentCount : int
+ Setup( name : string, code : string ) : void
+ AssignTeacher( id : int, name : string ) : void
+ AddStudent( id : int, name : string ) : void
+ DisplayCourseInfo(): void

Function name

AssignTeacher

Inputs

id, an int
name, a string

Returns

void

Given the input parameters id and name, call the m_teacher's set up function to set up the teacher's info.

Function name

AddStudent

Inputs

id, an int
name, a string

Returns

void

Add a new student to the m_students array and increment the m_studentCount afterwards.

Function name

DisplayCourseInfo

Inputs

None

Returns

void

Display the course name and code. Next call the teacher's Display function. Finally, create a for loop to iterate over the student array and call each student's Display function.


Writing the program

Go to the https://mockaroo.com/ website to generate example IDs and names to fill out here. (Set the ID field to a "number" type, and the name field to "Full Name").

  1. Create a new variable named cs134, initialized as a Course object.
  2. Call Setup and initialize its code to "CS134" and its name to "Programming Fundamentals".
  3. Call its AssignTeacher function, passing in a name and an id.
  4. Call its AddStudent function for at least four students, adding in names and ids generated with Mockaroo.
  5. Finally, call the DisplayCourseInfo function to display the course information.

The output will look like the example above.

Program 5: Basic inheritance

⭐⭐

For this execise we'll step through a very simple example of using inheritance.

RECTANGLES
Enter width: 4
Enter height: 3
The rectangle area is 12

CIRCLES
Enter radius: 5
The circle radius is 78.5            

Creating the project

Create a program that contains the files main.cpp, Shapes.h, and Shapes.cpp.


Implementing the classes


The Shape class

The Shape class will be the parent class of our other shapes. We're defining a CalculateArea function here, though it won't really do anything handy until we override it in the child classes.

The class declaration will look like this:

class Shape
{
    public:
    float CalculateArea();
};

And the function implementation will look like this:

float Shape::CalculateArea()
{
    return 0;
}
Shape
+ CalculateArea() : float

The Rectangle class

The Rectangle class inherits from the Shape class and will override the CalculateArea function. Additionally, a rectangle requires width and height information, as well as a function to interface with that data to set it up.

The class declaration will look like this:

class Rectangle : public Shape
{
    public:
    void Setup( float width, float height );
    float CalculateArea();

    private:
    float m_width;
    float m_height;
};

And the function definitions will look like this:

void Rectangle::Setup( float width, float height )
{
    m_width = width;
    m_height = height;
}

float Rectangle::CalculateArea()
{
    return m_width * m_height;
}
Rectangle, inherits from Shape
- m_width : float
- m_height : float
+ Setup( width : float, height : float ) : void
+ CalculateArea() : float

The Circle class

The Circle class inherits from the Shape class and will override the CalculateArea function. Additionally, a circle requires radius information, as well as a function to interface with that data to set it up.

The class declaration will look like this:

class Circle : public Shape
{
    public:
    void Setup( float radius );
    float CalculateArea();

    private:
    float m_radius;
};

And the function definitions will look like this:

void Circle::Setup( float radius )
{
    m_radius = radius;
}

float Circle::CalculateArea()
{
    return 3.14 * m_radius * m_radius;
}
Circle
- m_radius : float
+ Setup( radius : float ) : void
+ CalculateArea() : float

Implementing the program

We're not getting too deep into inheritance here, but if you take CS235 you will learn a lot more about ways inheritance can be used in an object oriented design.

Implement the following steps in main():

  1. Rectangle:
    • Create two float variables for width and height.
    • Ask the user to enter a width and a height and store them in the variables.
    • Create a Rectangle object, then use its Setup function to set up its width and height.
    • Display the resulting area by calling the CalculateArea function.
  2. Circle:
    • Create a float variable for radius.
    • Ask the user to enter a radius store it in the variable.
    • Create a Circle object, then use its Setup function to set up its radius.
    • Display the resulting area by calling the CalculateArea function.

Once run, the output should look like this:

RECTANGLES
Enter width: 4
Enter height: 3
The rectangle area is 12

CIRCLES
Enter radius: 5
The circle radius is 78.5