A9-Getting Classy

Table of Contents


Objectives

  • Develop classes and construct objects.
  • Hide data using the keyword private.
  • Write member functions that access private data.
  • Code multiple constructors to initialize private data.
  • Call member functions of objects.

Academic Honesty

Read the Scholastic Honesty Policy and Assignment Integrity policies of the syllabus. Here are some clarifications for this particular assignment:

  • You are encouraged to work with one other student of this class following the rules of Pair Programming for Homework Assignments. If you choose to pair program, there is a bonus applied.
  • You may not give a copy of your code to your designated pair-programming partner if you did not develop the code together.
  • You may not look at another student's code until you complete and submit this assignment, except for code you develop code together with your pair-programming partner.
  • You may get help from people other than your pair-programming partner if you get stuck, but only if they do not show or tell you the code to type.

Preparation

  1. Make sure you have completed the exercises from lesson 9.
  2. Complete the Review Exercises in CodeLab 9. These exercises will help prepare you for the problem-solving programs and should be completed first.

Project Specifications

Your solutions to these projects must use only techniques we have covered so far.

Programming Style

For all programs, remember to follow all the style rules we have covered, as well as the new rules, including:

  1. Class naming conventions (See: Class Names) new!
  2. Indentation in classes and placement of curly braces new!
  3. Every function declaration (prototype) in the class, including constructor functions, have a function comment block new!
  4. Every file has a file comment block
  5. No magic numbers (See: No Magic Numbers)

Dogs
Mary Bloom, AKC

Project 1: A Classy Dog

Dogs have long lived with humans, by some estimates 27,000 to 40,00 years [1]. Scientists believe wolves were first attracted to human camps to scavenge for leftover food. Over time, some wolves started traveling with the nomadic humans and a sort of natural selection for domestication occurred [2].

In modern times, dogs help people in many ways, including hunting, herding, pulling loads, protection, assisting police and military, companionship, aiding disabled people and therapeutic roles [3]. Dogs are often referred to as "Man's best friend" [4], though women were probably the first to make them pets [2].

Ever wonder why dogs are so lovable? Scientists have discovered that when people lock eyes with their dogs, the process generates the "love hormone" oxytocin in both the human and the dog. [5, 6]

Not all humans and dogs have positive experiences however. Each year, 4.5 million people are bitten by dogs [7]. All dogs may bite and one must learn how to prevent dog bites [8].

Project Specifications
  1. Write a declaration and a definition for a class named Dog along with a short main() function to test the class code. Review lesson 9.2.2 to get started.
  2. Name the source code file dog.cpp and include all your code in this single file.

    Be careful of the spelling, including capitalization, as you will lose points for a misspelled name. Naming is important in programming.

  3. Have no user input for this project. Testing of the program will be hard-coded in main().

    Do NOT use any keyboard input streams, like cin, in this project. If you have a cin statement in your code, you will get a low score.

  4. The Dog class must contain exactly (no more and no less than) two member variables declared private:
    1. string name
    2. int age
    See lesson 9.2.3 for an example of data members.
  5. Declare only the following functions (prototypes) inside the class braces and separately define (implement) the functions outside the class declaration (curly braces of the class):
    1. A default constructor that sets the name to "Puppy" and the age to 0. See lesson 9.2.5 for an example constructor.
    2. A two-parameter constructor that sets the name and age member variables to the parameter values. The parameters must be coded in the order of name followed by age. See lesson 9.3.2 for multiple examples of constructors.
    3. One "get" function for each of the member variables that returns the member variable's current value. The name of the function must follow the naming standards for "get" functions, which is the name of the variable with the prefix word "get". Include the const keyword.
    4. Write a member function for the Dog class named sleep() with the following signature:
      /**
          Causes this dog to sleep.
      */
      void sleep() const;
        
      Call the function at least once in your story. When called, the function prints three or more z's to the console, like:
      Zzzz
      
    5. Write a member function for the Dog class named speak() with the following signature:
      /**
          Randomly selects and prints a single sound from the sounds array.
      
          @param sounds An array of sounds to choose from.
          @param size The number of elements in the array.
      */
      void speak(const string sounds[], int size) const;
      

      Call the function at least once in your story. When called, the function selects one of the sounds from the array parameter at random and prints one of the sounds made by a Dog. The four possible sounds made by a Dog for this project are: "aullar", "ladrar", "bark", and "howl". All are printed without the double quotes.

  6. All non-mutator functions must include the keyword const as discussed in lesson 9.3.4 under Accessor Functions and in the textbook on pages 402-403 under the section on, "const Correctness".
  7. Example Run: In your main() function, construct two or more Dog objects, using both the default constructor and the overloaded constructor. Then write a story that calls all the member functions of the class at least one time. For example:
    Meet my new dog Puppy.
    He plays with my 9 year old dog Mago.
    My dog Mago knows two commands.
    Mago speak!
    Mago says: ladrar!
    Mago sleep!
    Mago says: Zzzz
    

    In the above example story, the text in aqua italics shows the output of member functions calls. Your program does NOT print the characters using colors or italics. Have fun and make up your own dog story. See lessons 9.2.3 and 9.3.3 for how to construct objects from classes. See lesson 9.3.4 on how to access member variables.

  8. After displaying the story, exit the program.
  9. Submit this project with the rest of the assignment as described in Deliverables.
Hints:
  • We only need the functions listed in the specifications above, though there is no penalty for adding more functions in this project. However, consider if another function is actually needed before adding one. Best practice is to minimize the functions provided in a class to only those needed.
  • To make a dog say different things every time the program runs, see lesson 7.3.4: Seeding the Random Generator.
References and More Information
  1. Ancient wolf genome reveals an early divergence of domestic dog ancestors and admixture into high-latitude breeds: Current Biology, Volume 25, ISSUE 11, P1515-1519, June 01, 2015
  2. The History of Dogs as Pets: ABC News
  3. Dog: Wikipedia article.
  4. Man's best friend (phrase): Wikipedia article.
  5. Oxytocin-gaze positive loop and the coevolution of human-dog bonds: Science Magazine
  6. Dogs, Humans, and the Oxytocin-Mediated Strong Social Bond: Psychology Today
  7. National Dog Bite Prevention Week®: American Veterinary Medical Association (AVMA)
  8. Preventing Dog Bites: Centers for Disease Control and Prevention

Image
Image source

Project 2: A Classy Credit Card

In this project we create a simple class for a credit card database. A credit card is a payment authorization to enable the cardholder to pay a merchant for goods and services [1]. The card user must have promised a bank to pay them the amounts and other agreed to charges. Many of us have a credit card or have used credit cards.

When we declare a class, we create a model of an object in software. Credit cards are complex and to be efficient, we create an abstraction of what we are modeling. Abstraction is the reduction of a concept or idea to the most simple or basic of shared characteristics. Once we develop a class, we may create many objects from the class.

Our class CreditCard will contain the information we need to store multiple credit cards along with a programming interface to access the credit card data. In addition we will write a short main() function to test our code.

Project Specifications
  1. Write a declaration and a definition for a class named CreditCard along with a short main() function to test the class code.
  2. Name the source code file credit.cpp and include all your code in this single file.

    Be careful of the spelling, including capitalization, as you will lose points for a misspelled name. Naming is important in programming.

  3. Have no user input for this project. Testing code for the program is hard-coded in main().

    Do NOT use any keyboard input streams, like cin, in this project. If you have a cin statement in your code, you will get a low score.

  4. The CreditCard class must contain exactly (no more and no less than) four member variables declared private:
    1. int cardId (card number)
    2. string custName (customer name)
    3. double limit (credit limit)
    4. double rate (annual percentage rate)
  5. Declare only the following functions (prototypes) inside the class braces and separately define (implement) the functions outside the class declaration (curly braces of the class):
    1. A default constructor that sets the numerical types to zero (0).
    2. A four-parameter constructor that sets the cardId, custName, limit, and rate member variables to the parameter values. The parameters must be coded in the order of cardId, custName, limit, and rate.
    3. One "get" function for each of the member variables that returns the member variable's current value. The name of the function must follow the naming standards for "get" functions, which is the name of the variable with the prefix word "get". Include the const keyword.
    4. One "set" function for each member variable with a single parameter that sets a value for a member variable. The name of the function must follow the naming standards for "set" functions, which is the name of the variable with the prefix "set".
    5. Accessor function print() that has no parameters and returns no values, but displays the data of the object all on one line, followed by a newline character, like this:
      Ima Poore                  942      300.50    79.9
      Text must be left justified with left and numbers right justified using right and with the correct number of decimal places. To ensure the correct number of decimal places for any number use both fixed and setprecision() in print(). The data displayed in order are:
      1. custName
      2. cardId
      3. limit
      4. rate

      Notice that the print order is different than the order in the constructor.

    6. Do not add any extra member functions beyond the above.

    Note: even though you must write the get functions, you may not need to actually call them for this assignment. We will be using the get functions in future assignments.

  6. All non-mutator functions must include the keyword const as discussed in lesson 9.2.4 under Accessor Functions and in the textbook on pages 402-403 under the section on "const Correctness".
  7. In the credit.cpp file, write a main() function to do the following:
    1. Construct at least three CreditCard objects.
    2. Set values (cardId, custName, limit, and rate) for one or more objects using the four-parameter constructor, and for one or more objects using the default constructor followed by calling all the "set" functions to assign values. Make certain at least one limit and one rate has a decimal place of zero (.0) to verify correct alignment.
    3. Display output for all 3+ objects as shown in the Example Output specification including the column headings.

    Have no user input for this project. Instead write code to do the above in main() for testing. Do NOT use any keyboard input streams, like cin, in this project. If you have a cin statement in your code, you will get a low score.

  8. Example Run: When you run the program you must see the following output without any user input.
    Credit Cards:
    Customer Name          Card ID       Limit   Rate%
    Ima Poore                  942      300.50    79.9
    Mark Zuckerberg            943   200000.00    11.0
    Bill Gates                 944   300000.00    10.5
    

    You may change the spacing between columns but columns must line up as shown, with names left justified and numbers right justified. Feel free to come up with your own customer names and other data.

  9. Create the correct spacing for the output using the setw() formatting manipulator described on pages 49-51 (1/e: 53-55) of the textbook. In addition, use the formatting manipulator left for text and right for numbers to ensure correct alignment for all data. To make use of these manipulators include the iomanip library. For example:
    cout << setw(22) << left << custName; // aligns data left in 22 character field
    
  10. After displaying the output, exit the program.
  11. Submit the source code file credit.cpp with the rest of the assignment as described in Deliverables.
Hints:
  • The width constants in the example run are
    const int ID_WIDTH = 8;
    const int NAME_WIDTH = 22;
    const int LIMIT_WIDTH = 12;
    const int RATE_WIDTH = 8;
    
  • Do NOT put const variables inside the class. See spec 4 above.
References and More Information
  1. Credit Card: Wikipedia article

Extra Credit

The following are worth extra credit points if the main program works well:

  1. Complete the assignment using pair programming. (2 points)
  2. Add a function named toString() to class CreditCard that has no parameters and returns a string containing all the data about the credit card. Call the function one time in the main() function to show that it works. (2 points)

    The function does NOT print any values and must NOT use cout. Instead, the function must return a string with one line of text like that shown below.

    Ima Poore                  942      300.50    79.9
    

    Once returned, print the string within main() using code like:

    cout << poore.toString() << endl;
    

    Note that this extra credit will require you to convert numbers to strings. Research stringstream for the conversion and provide an attribution for the source of your stringstream information, either a URL or book and page number. No attribution means no credit.

Make certain that your README.txt file describes any extra credit attempted.

Tutorial Lab

In preparation for next weeks lessons, complete the following:

  1. Read the assigned reading in the textbook
  2. Complete the Tutorial Exercises in CodeLab 9 before the specified due date.

    Refer to the assigned reading for the next lesson to help you understand the problems. Also, you can use the online lecture notes for more information as the notes become available. You can look at solutions if you miss your first few attempts and are stuck by clicking the "Solution" tab.

Grading Criteria

The instructor will evaluate your assignment using the following criteria. Thus you should check your assignment against these criteria to maximize your score.

Each criteria represents a specific achievement of your assignment and has a scoring guide. The scoring guide explains the possible scores you can receive. Some scoring guides have a list of indicators. These indicators are a sign of meeting, or a symptom of not meeting, the specific criterion. Note that a single indicator may not always be reliable or appropriate in a given context. However, as a group, they show the condition of meeting the criterion.

For information on grading policies, including interpretation of scores, see the syllabus.

Lesson Exercises

  • 2: All lesson exercises attempted and turned in
  • 1: Some lesson exercises completed and turned in
  • 0: No lesson exercises completed or turned in

Class Functionality (x2)

  • 7: Demonstrates mastery of the assignment.
    • Applies concepts from the lessons appropriately
    • Meets all specifications with particularly elegant solutions
    • Runs to completion with no abnormal error conditions
    • Generates correctly formatted output
  • 6: Has all the functionality expected of the assignment with mostly correct formatting.
    • Demonstrates many techniques from the lesson
    • Attempts to meet all specifications
    • Generates correctly formatted output given correct input
    • May have one minor formatting error
  • 5: Has most of the functionality and format expected of the assignment
    • Demonstrates many techniques from the lesson
    • Attempts to meet all specifications
    • Implementation seems more complicated than necessary.
    • May have one or more formatting errors in output
    • May have one minor functional error
  • 4: Has most of the functionality expected of the assignment
    • Demonstrates some techniques from the lesson
    • Attempts to meet all but one of the specifications
    • Implementation seems excessively complicated.
    • May have many formatting errors in output
    • May have 2-3 minor functional errors
  • 3: Has some of the functionality expected of the assignment
    • Attempts to meet at least 1/2 of the specifications
    • Demonstrates many techniques from the lessons
    • Implementation seems excessively complicated.
    • May have more than 3 minor functional errors
    • Source code compiles with no errors or warnings
  • 2: Serious functional problems but shows significant effort and understanding
    • Attempts to meet less than 1/2 of the of the specifications
    • Has a major error or many minor errors
    • Implementation seems very convoluted
    • Demonstrates few techniques from the lessons
    • Source code compiles but may have multiple warnings
  • 1: Serious functional problems but shows some effort and understanding.
    • Does not compile but shows an attempt to meet most specifications
    • Implementation seems somewhat complete but has errors
    • Demonstrates some techniques from the lessons
  • 0: Minimal to no work apparent or made in an incorrect way.
    • Not turned in
    • Does not compile with little work apparent
    • Attempts to meet less than 1/2 of the of the specifications
    • Uses techniques not covered in the course so far

Program Style

  • 4: Code is well-documented including:
  • 3: Code has a minor documentation error.
  • 2: Code has some documentation errors or a missing file.
  • 1: Code has many documentation errors or a missing file and some errors.
  • 0: No apparent attempt to follow documentation standards or write documentation comments

CodeLab and Other Tutorial Exercises

Number completed correctly / number exercises * 8 and rounded up to the nearest integer.

README.txt File

  • 2: README.txt file submitted following the instructions
  • 1: README.txt file submitted but some information was missing
  • 0: No README.txt file submitted

Total possible: 30, plus extra credit

Deliverables

Submit your assignment to Canvas, in the assignment folder A9-Getting Classy, following the instructions for submitting homework. Include the following items for grading:

  1. README.txt file
  2. All the exercise files from Lesson 9
  3. dog.cpp
  4. credit.cpp

Your assignment must work as submitted, so submit all the files needed to complete your assignment. Remember to test and double check your files before submitting them. If you make a mistake, you can resubmit up to the deadline. If you resubmit, you must include all your assignment files in the last submission as Canvas hides prior submissions.

Last Updated: November 13 2019 @18:42:54