Introduction to classes cont.

This lesson contains approximately 45 minutes of video content.

Constructors and destructors

In-class member initializers

Public / private distinction

Interfaces

Private member functions

Non-member "helper" functions

Activity: Running total class implementation

Graded Playground Autograder

Activity Prompt:

Define the class RunningTotal according to the following specification. Be sure to include the necessary header files. The solution constraints section give some hints on which headers will be needed.

Private data members

  • total_ typed int
  • history_ typed std::vector<RunningTotalHistoryEntry>

Public member functions

Remember to declare the member functions that do not modify object state as const.

  • RunningTotal(), a default constructor that initializes total_ with 0.
  • CurrentTotal()
    • Returns the value stored in total_
    • Therefore, the return type of CurrentTotal() is int
  • Add(int value)
    • Increments the RunningTotal object's total_ data member with value.
    • Pushes back to the RunningTotal object's history_ an RunningTotalHistoryEntry whose operation is + and value is that stored in this function's value parameter.
  • Subtract(int value)
    • Decrements the RunningTotal object's total_ data member with value.
    • Pushes back to the RunningTotal object's history_ an RunningTotalHistoryEntry whose operation is - and value is that stored in this function's value parameter.
  • History()
    • Returns an std::string representation of the contents of the RunningTotal object's history_ according to the prescribed format that follows.
      • The string will always begin with 0
      • For each element in history_, visited from the first element (that at index 0) to the last element (that at index history_.size() - 1).
        • Concatenate the visited RunningTotalHistoryEntry object's operation value to the string.
        • Concatenate the visited RunningTotalHistoryEntry object's value to the string. To do this, you must convert the integer value to an std::string using std::to_string.
    • Return the std::string you have constructed to the caller.
    • Example:
      • RunningTotal rt;
        rt.Add(10);
        rt.Subtract(1);
        rt.Add(5);
        rt.History(); // returns the following std::string: "0+10-1+5"
                    

Graded Files

Only the following files are transferred to the autograder.

  • running-total.hpp
  • running-total.cc
#include "running-total.hpp" int main() { }
#ifndef RUNNING_TOTAL_HPP #define RUNNING_TOTAL_HPP #endif
#include "running-total.hpp"
#ifndef RUNNING_TOTAL_HISTORY_ENTRY_HPP #define RUNNING_TOTAL_HISTORY_ENTRY_HPP struct RunningTotalHistoryEntry { char operation = '\0'; int value = 0; }; #endif