Schedule‎ > ‎

Assignment 9 Getting Classy

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:

  • Most importantly, you undermine your own self confidence when you cheat, because you know you didn't accomplish the assignment without cheating.
  • You may not give/show/post a copy of your code to anyone else.
  • You may not look at another student's code until you complete and submit this assignment.
  • You may get help from other people but only if they do not show or tell you the code to type.
  • Remember that the instructor performs similarity tests on programming project submissions, and copied or plagiarized code is usually very easy to detect.


Grading Criteria (30pts + Extra Credit 4pts)

For each part: 10 pts: File Header 1pt, Function Headers 1pt, Compiles 2pts, Proper Formatting 1pt, Works as Specified 10pts
  1. bear.cpp (15pts)
  2. person.cpp (15pts)
  3. Extra Credit: xcmealfun.cpp (4pts)
Total Possible: 30 pts + Extra Credit 4pts


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 new!
  2. Indentation in classes and placement of curly braces new!
  3. Every nontrivial function declaration (prototype) in the class have a function comment block.  Trivial functions are accessors/mutators and constructors unless they do a calculation or other logic.  All other class functions must have a function comment block.  new!
  4. Every file has a file comment block
  5. No magic numbers (See: No Magic Numbers)



Project 1: A Bear Class

American black bears live in North America, ranging from Canada to Mexico. Black bear adult males weigh about 300 to 400 pounds. Because of their smaller size, they can climb trees. Typically these bears are black in color but coat colors range from white, blond, cinnamon, or light brown to dark chocolate brown or to jet black, with many intermediate variations existing. Black bears eat mostly vegetation, such as berries, but sometimes eat fish and other animals. 

Grizzly bears are larger, with adult males weighing between 800 and 1200 pounds on average. Their fur color ranges from blond to nearly black but is typically brown. They also live in the north, many in Alaska and the northern parts of Asia. Their  diet is omnivorous, including berries, fish, and moose.                                                                                                                            

Polar bears inhabit arctic regions of the world, such as northern Canada and Alaska. Their fur color is transparent but looks white because of the surrounding snow and ice. Polar bears are very large, with adult males weighing an average of 1000 pounds. The most carnivorous of the bear family, their diet consists of primarily of seals. However, they also eat other foods such as birds, reindeer, and even other polar bears when seals are not available. 

Project Specifications
  1. Write a declaration and a definition for a class named Bear along with a short main()function to test the class code.
  2. You must name the source code file bear.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 Bear class must contain at least these three member variables declared private:
    1. string type
    2. int weight
    3. string color
  5. Write function declarations (prototypes) inside the class and separately define (implement) all the functions outside the class declaration (curly braces of the class).
  6. Write a default constructor that sets the type to "Black", the weight to 350 and the color to "Black".
  7. Write a three-parameter constructor that sets the typeweight and color member variables to the parameter values. The parameters must be coded in the order of typeweight and color.
  8. Write one "get" function for each of the member variables that returns the 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".
  9. 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".
  10. In your main() function, construct three Bear objects, one of each type. You must use the default constructor to construct one of your bears.  Compile and run your code to make sure it works at this point.
  11. Then write a story that calls all the member functions of the class at least one time. For example:
    ***My Bear Stories***
    Once when I was hiking a saw a brown mother bear with two cubs.
    I knew that all Grizzly bears are dangerous, especially mother
    bears if they are protecting their cubs. My companion and I slowly
    backed away and the bears went the other way.
    When I was in Glacier Park a few years, one of the rangers was biking
    and came upon a bear. Unfortunately, the bear killed him.
    I have never seen a Black bear but know they mostly eat vegetation.
    Even so, at 350 pounds, be careful and carry your bear mace when
    hiking in bear country.
    Polar bears are endangered because of global warming. At the zoo a white Polar bear weighing 1000 pounds gets a meal of fortified meat, dog kibble and fish.
    The Polar bear eats the fish first. Yum!
    

    In the above example story, the text in  yellow shows the output of member functions calls. Your program can only use member function calls to generate those words. Your program does not need to print yellow letters.  You can make up your own bear story as long as it uses all of your accessor methods.

  12. After displaying the story, exit the program.
  13. Submit this project with the rest of the assignment.
References and More Information
  1. American black bear: Wikipedia article.
  2. Grizzly bear: Wikipedia article.
  3. Polar bear: Wikipedia article.









Project 2: A Classy Person

When we declare a class, we create a model of an object in software. To be effective, 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 have determined the essential characteristics, we provide ways to generalize the class. Generalization is about developing a general solution that works for a range of similar problems. Once we develop a class, we may create many objects from the class.

In this project, we create a simple abstraction of a person. We will declare a programming interface and define the functions for that interface. In addition we will write a short main() function to test our interface.

Project Specifications
  1. Write a declaration and a definition for a class named Person along with a short main()function to test the class code.
  2. Name the source code file person.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().                                                                                                                                                                  
  4. Do NOT use any keyboard input streams, like cin, in this project. If you have a cinstatement in your code, you will get a low score.
  5. The Person class must contain at least these three member variables declared private:
    1. string name
    2. int age
    3. double income
  6. Write the following function declarations (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 three-parameter constructor that sets the nameage and income member variables to the parameter values. The parameters must be coded in the order of nameage and income.
    3. One "get" function for each of the member variables that returns the 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".
    4. One "set" function for each member variable that sets a new value. 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 like this:
      Emma Hacker           24   71916.00
      Text must be left justified and numbers right justified with the correct number of decimal places. The data displayed in order are:
      1. name
      2. age
      3. income
    6. Do not add any extra member functions than 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.

  7. 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".
  8. In the person.cpp file, use the specified main() function to do the following:
    1. Construct at least the three Person objects.
    2. Set values (name, age and income) for two objects using the three-argument constructor and for one object using the default constructor and "set" functions.
    3. Display output for all 3 objects as shown in the Example Output specification.

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

  9. Example Run: When you run the program you must see the following output without any user input.
    Persons of Interest:
    Name                 Age     Income
    Sophie Engineer       42  102280.00
    Emma Hacker           24   71916.00
    John Q Public         37   55775.42
    

    You may change the spacing between columns but columns must line up as shown, with names left justified and numbers right justified with two decimal points.

  10. 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, you will need to use the left and right formatting manipulators. To use these manipulators, include the iomanip library. Align text or numbers in a setw() field using left or right to align the data. For example:
    cout << setw(18) << left << name; // aligns data left in 18 character field
    
  11. After displaying the output, exit the program.
  12. Submit the source code file person.cpp with the rest of the assignment.
Hints:
  • The width constants in the example run are
    const int NAME_WIDTH = 18;
    const int AGE_WIDTH = 6;
    const int INCOME_WIDTH = 11;
    
  • Do NOT put const variables inside the class. Put them as global constants at the top of your file.


Extra Credit (4 pts)

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

  1. Add an extra member function eat() to the Bear class with the following signature: (2 points)
    /**
        The bear randomly chooses one of the offered foods to eat and
        prints the food surrounded by # marks.
    
        @param food An array of foods to eat.
        @param size The number of elements in the array.
    */
    void eat(string food[], int size) const;
    
    Call the function at least once in your story. When called, the function selects one of the foods at random and prints the type of the bear and the name of the food consumed surrounded by # marks like:
    The Polar bear eats the #dog kibble#. Yum!
    

    Hints: See lesson 7.2.5 to review how to declare arrays and lesson 7.3.6 to review random numbers.

  2. Add a function named toString() to class Person that has no parameters and returns a string value containing all the data about the person. Call the function one time 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.

    Emma Hacker           24   71916.24
    

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

    cout << emma.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.

Solution Code:

bear.cpp

/**

    CS-11 Asn 9, bear.cpp

    Purpose: bear class to tell a story


    @author Sharon Strelitz

    @version 1.0  02/20/2018

 */

#include <iostream>

using namespace std;


class Bear {

  public:

    Bear();  //default Constructor

    Bear(string newType, int newWeight, string newColor);

    string getType() const;

    int getWeight() const;

    string getColor() const;

  private:

    string type;

    int weight; 

    string color;

};


Bear::Bear()  {

  type = "Black";

  weight = 350;

  color = "Black";

}


Bear::Bear(string newType, int newWeight, string newColor){

  type = newType;

  weight = newWeight;

  color = newColor;

}

 

string Bear::getType() const {

        return type;

}


int Bear::getWeight() const {

        return weight;

}

string Bear::getColor() const {

        return color;

}

int main() {

  Bear bear1;

  Bear bear2("Grizzly", 1200, "Brown");

  Bear bear3("Polar", 1500, "White");

  cout << "***My Bear Stories***" << endl;

  cout << "Once when I was hiking I saw a " << bear2.getColor() 

       << " mother bear with two cubs." << endl;

  cout << "I knew that all " << bear2.getType() << " bears are dangerous," 

       << " especially mother bears " << endl;

 cout << "if they are protecting their cubs." << endl;


  cout << "My companion and I slowly " 

       << "backed away and the bears went the other way. " << endl << endl;

  cout << "When I was in Glacier Park a few years, one of the rangers "

       << "was biking and came upon a bear. Unfortunately, the bear killed him. " << endl << endl;

  cout << "I have never seen a " << bear1.getType() 

       << " bear but know they mostly eat vegetation.  "

       << "Even so, at " << bear1.getWeight() << " pounds, be careful and ";

  cout << "carry your bear mace when hiking in bear country." << endl << endl;

  cout << bear3.getType() << " bears are endangered because of global warming. "

       << "  At the zoo a " << bear3.getColor() << " " << bear3.getType()

       << " weighing " << bear3.getWeight() << " pounds gets a meal of fortified meat, "

       << "dog kibble and fish.  The " << bear3.getType() << " eats the fish first.  Yum!" << endl;

}


person.cpp

/**
    CS-11 Asn 9, person.cpp
    Purpose: Store info about a person

    @author Sharon Strelitz
    @version 1.0  02/20/2018
 */
#include <iostream>
#include <iomanip>
using namespace std;
const int NAME_WIDTH = 18;
const int AGE_WIDTH = 6;
const int INCOME_WIDTH = 11;

class Person {
  public:
    Person();  //default Constructor
    Person(string newName, int newAge, double newIncome);
    string getName() const;
    int getAge() const;
    double getIncome() const;
    void setName(string newName);
    void setAge(int newAge);
    void setIncome(double newIncome);
    /**
    print:  print the information about a person

    @param  no input parameters
    @return void
    */
    void print const();
  private:
    string name;
    int age; 
    double income;
};

Person::Person()  {
  name = "";
  age = 0;
  income = 0;
}

Person::Person(string newName, int newAge, double newIncome){
  name = newName;
  age = newAge;
  income = newIncome;
}
 
string Person::getName() const {
        return name;
}

int Person::getAge() const {
        return age;
}
double Person::getIncome() const {
        return income;
}
void Person::setName(string newName) {
        name = newName;
}

void Person::setAge(int newAge) {
        age = newAge;
}
void Person::setIncome(double newIncome) {
        income = newIncome;
}

void Person::print() const {
    cout << fixed << setprecision(2);
    cout << setw(NAME_WIDTH) << left << getName();
    cout << setw(AGE_WIDTH) << right << getAge();
    cout << setw(INCOME_WIDTH) << right << getIncome() << endl;  
}

int main() {
  Person person1;
  person1.setName("Jose Engineer");
  person1.setAge(30);
  person1.setIncome(100000);
  Person person2("Maria Engineer", 22, 100000);
  Person person3("John Driver", 30, 12000);
  cout << setw(NAME_WIDTH) << left << "Name";
  cout << setw(AGE_WIDTH) << right << "Age";
  cout << setw(INCOME_WIDTH) << right << "Income" << endl;  
  person1.print();
  person2.print();
  person3.print();

}


Comments