11: Objects and Classes

General Information

Housekeeping

Announcements

See Announcements link in Canvas to keep up with what is going on. Here are a few for review:

Questions from last class or reading?

Homework Questions?

Learning from the Exam

Learner Outcomes

At the end of the lesson the student will be able to:

  • Know what was missed on the midterm
  • Decide on what to do to improve performance as needed

Post Exam Decisions

Exam Results

Exam Retake

Compiler Errors

Learning from the Exam

Post Exam Survey

forked road

Making Decisions

Last Day to Withdraw Approaching

Why Learn to Program?

Image

Jobs of the Future

Jobs that won't exist in 2030 (via PricewaterhouseCoopers)

1. Uber drivers
2. Truck drivers
3. Cashiers
4. Librarians
5. Postal Couriers
6. Bank Tellers
7. Sales
8. Pilots
9. Sports Referees & Umpires
10. Textile Workers
11. Telemarketers
12. Retail Clerks
13. Waiters
14. Data Entry
11. Telemarketers
12. Fisherman
13. Waiters
14. Data Entry
15. Tax Preparers
16. Insurance Underwriters
17. Tax Collectors
18. Cargo & Freight Agents
19. Legal Secretaries
20. Accountants
21. Radio Analysts
22. Credit Analysts
23. Tax Preparers
24. Tellers
25. Lumberjacks
26. Etchers & Engravers
27. Manicurists
28. Loan officers
29. Farm Labor
30. Dental Laboratory Technicians
31. Pesticide Handlers
32. Fisherman
33. Real Estate Brokers
34. Restaurant Hosts & Hostesses
35. Receptionists
36. Gaming Dealers
37. Ushers / Ticket Takers
38. Bill & Account Collectors
39. Nuclear Power Reactor Operators
40. Electrical and Electronic Equipment Assemblers
41. Landscaping and Groundskeeping Workers
42. Auditors
43. Waiters & Waitresses
44. Budget Analysts
45. Bicycle Repairers
46. Tire Builders
47. Jewelers and Precious Stone and Metal Workers
48. Cement Masons
49. Welders
50. Agricultural Inspectors
51. Paralegals and Legal Assistants
52. Pharmacy Technicians
53. Insurance Sales Agents
... and many more

More Information

11.1: Cooperative Quizzes

Quiz Part 1: Individual Readiness Assessment

Quiz Part 2: Team Readiness Assessment (20m)

Quiz Appeals

11.2: Defining a Class

Reviewing Class Definitions

Class Declaration Syntax

Example Class Definition

Private Members and Information Hiding

Example Defining a Class

#include <iostream>
using namespace std;

class Product
{
    public:
    void read();
    void print() const;

    private:
    string name;
    double price;
};

// For testing
int main()
{
    // Construct objects here

    return 0;
}

Camel Case

Programming Style: Class Naming Conventions

Exercise 11.2: Coding Class Definitions (5m)

In this exercise we define a class.

For this exercise we break into teams. Within the team, work with each other to develop a solution.

Specifications

  1. Start Repl.it and copy the following code into the code editor.
    #include <iostream>
    using namespace std;
    
    int main() {
        // Enter your code here
    
        return 0;
    }
    

    We will call this code file car.cpp and add to it in the next 3 exercises.

  2. Declare a class named Car, and then compile your code to check for syntax errors.

    Remember the semicolon after the closing curly brace.

  3. Declare private member variables for a name, price and mpg (miles per gallon) with the appropriate data types.
  4. Declare two public prototypes for functions named read() and print() with void return types and no parameters.
  5. Compile and run the modified program to make sure you made the changes correctly.

    The program should compile without error or warning. When you run, nothing should happen yet.

  6. Save your source code file as we will be adding to it in the next Exercise.

When finished developing your code click hereClick to show answer to verify. Code need not look exactly the same. After you have completed your own program, reviewing another is often helpful in learning how to improve your programming skills.

11.3: Data Members and Objects

Reviewing Data Members and Objects

Constructing an Object

Example Code

#include <iostream>
using namespace std;

class Product
{
    public:
    void read();
    void print() const;

    private:
    string name;
    double price;
};

// For testing
int main()
{
    Product milk;
    Product bread = Product();

    return 0;
}

Exercise 11.3: Coding Data Members and Objects (2m)

In this exercise we code an object for our class.

For this exercise, since it is short and easy, we will stay together as a class.

Specifications

  1. Continue with your source code from the last Exercise.
  2. In the main() function, define a Car object (Car class variable) like:
    int main() {
        Car tesla;
    
        return 0;
    }
    
  3. Compile and run the modified program to make sure you made the changes correctly.

    The program should compile without error or warning. When you run, nothing should happen yet.

  4. Save your source code file as we will be adding to it in the next Exercise.
  5. Think about this question: What does defining and compiling a Car variable tell us about class and objects?

When finished developing your code click hereClick to show answer to verify. Code need not look exactly the same. After you have completed your own program, reviewing another is often helpful in learning how to improve your programming skills.

11.4: Member Functions

Reviewing Member Functions

Member Function Definition Syntax

Mutator Functions

Accessor Functions

Dot Notation

Example Class Code with Member Functions

#include <iostream>
using namespace std;

class Product
{
    public:
    void read();
    void print() const;

    private:
    string name;
    double price;
};

void Product::read() {
    cout << "Enter a product name: ";
    cin >> ws;
    getline(cin, name);
    cout << "Enter the price for a " << name << ": ";
    cin >> price;
    cout << "You entered: ";
    print();
}

void Product::print() const {
    cout << name << " @ " << price << endl;
}

// For testing
int main()
{
    Product milk;
    milk.read();
    cout << "Printing in main(): ";
    milk.print();

    return 0;
}

Member Functions Calling Member Functions

Set Functions

Get Functions

Exercise 11.4: Coding Member Functions (10m)

In this exercise we code member functions.

For this exercise we break into teams. Within the team, work with each other to develop a solution. When the team has finished, choose one member to show your solution to the class by sharing your screen. The instructor will ask one team to share their solution.

Specifications

  1. Continue with your source code from the last Exercise in repl.it.
  2. After the class declaration, add the implementation (definition) of the mutator function read() that asks for the name, price and mpg of a car.

    Compile your code to verify you wrote it correctly.

  3. After the class declaration, add the definition of the accessor function print() that prints the name, price and mpg of a car object.

    Compile your code to verify you wrote it correctly.

  4. Change the main() function to call the member functions like:
    int main() {
        Car tesla;
        tesla.read();
        tesla.print();
    
        return 0;
    }
    
  5. Compile your code to make sure it has correct syntax. Run the code and verify you see input and output like the following:
    Enter the name of the car: Tesla 3
    Enter the price for a Tesla 3: 35000
    Enter the MPG for a Tesla 3: 134
    Tesla @ 35000 with MPG 134
    

    User input is shown in aqua italics for the example only, NOT your program.

  6. Once satisfied with your code, copy it into a text editor, save the file as "car.cpp", and submit the file to Canvas with the rest of the exercise files for the week.

When finished developing your code click hereClick to show answer to verify. Code need not look exactly the same. After you have completed your own program, reviewing another is often helpful in learning how to improve your programming skills.

CA 11.4: Challenge activities

Any problems with any of these Challenge activities? (Zybooks sign in)

If so, list the CA numbers in Chat

11.5: Constructors

Reviewing Constructors

Adding a Constructor

Example Class with a Constructor

#include <iostream>
using namespace std;

class Product {
    public:
    Product();
    void read();
    void print() const;

    private:
    string name;
    double price;
};

Product::Product() {
    name = "none";
    price = 0.0;
}

void Product::read() {
    cout << "Enter the name of the product: ";
    cin >> ws;
    getline(cin, name);
    cout << "Enter the price for a " << name << ": ";
    cin >> price;
}

void Product::print() const {
    cout <<  name << " @ " << price << endl;
}

// For testing
int main() {
    Product milk;
    Product bread;

    cout << "Enter the milk product data\n";
    milk.read();

    cout << "\nEnter the bread product data\n";
    bread.read();

    milk.print();
    bread.print();

    return 0;
}

In-class Member Initializers

CA 11.5: Challenge activities

Any problems with any of these Challenge activities? (Zybooks sign in)

If so, list the CA numbers in Chat

Exercise 11.5: Coding Constructors (10m)

In this exercise we explore the use of constructors.

For this exercise we break into teams. Within the team, work with each other to develop a solution. When the team has finished, choose one member to show your solution to the class by sharing your screen. The instructor will ask one team to share their solution.

Specifications

  1. Continue with your source code from the last Exercise in repl.it.
  2. In main(), add a call to the member function print() function before the call to the member function read(), like:
    int main() {
        Car tesla;
        tesla.print();
        tesla.read();
        tesla.print();
    
        return 0;
    }
  3. Compile and run your program and notice the output of member function print() before calling read(). It should look something like:
     @ 2.32211e-322 with MPG 6.89746e-308
    Enter the name of the car: Tesla 3
    Enter the price for a Tesla 3: 35000
    Enter the MPG for a Tesla 3: 134
    Tesla @ 35000 with MPG 134
    

    User input is shown in aqua italics for the example only, NOT your program. Notice that before calling read(), the print() function shows garbage output. After calling read(), the output is correct. Why do you think the first call to print() produces garbage output? Click to show answer

  4. Add a constructor declaration to the class specification. Your class structure should now look like:
    class Car {
        public:
        Car();
        void read();
        void print() const;
    
        private:
        string name;
        double price;
        double mpg;
    };
    
  5. After the class declaration,, add the following constructor definition.
    Car::Car() {
        name = "none";
        price = 0;
        mpg = 0;
    }
    
  6. Compile and run your program and notice the output of member function print() before calling read(). It should look like:
    none @ 0 with MPG 0
    Enter the name of the car: Tesla 3
    Enter the price for a Tesla 3: 35000
    Enter the MPG for a Tesla 3: 134
    Tesla 3 @ 35000 with MPG 134
    

    User input is shown in aqua italics for the example only, NOT in your program. Notice that calling the print() function before read() now shows the default values assigned by the constructor.

  7. Once satisfied with your code, copy your code into a text editor, save the file as "ctor.cpp", and submit the file to Canvas with the rest of the exercise files for the week.

When finished developing your code click hereClick to show answer to verify. Code need not look exactly the same. After you have completed your own program, reviewing another is often helpful in learning how to improve your programming skills.

11.6: Constructor Overloading

Reviewing Constructor Overloading

Multiple Constructors

Example: Default Constructor (No Parameters)

Example: Constructor Definition with one Parameter

Example: Constructor Definition with two Parameters

Implicit Default Constructors

Constructing Objects from Overloaded Constructors

Avoiding the No-Parameter Trap

CA 11.6: Challenge activities

Any problems with any of these Challenge activities? (Zybooks sign in)

If so, list the CA numbers in Chat

Exercise 11.6: Coding Overloaded Constructors (10m)

In this exercise we add and remove elements from the end of a vector.

For this exercise we break into teams. Within the team, work with each other to develop a solution. When the team has finished, choose one member to show your solution to the class by sharing your screen. The instructor will ask one team to share their solution.

Specifications

  1. Continue with your source code from the last Exercise in Repl.it.
  2. Add a constructor declaration with three parameters to the class specification like the following:
    Car(string newName, double newPrice, double newMpg);
    
  3. After the class declaration, add a constructor definition (implementation) for the above constructor.
    Car::Car(string newName, double newPrice, double newMpg) {
        name = newName;
        price = newPrice;
        mpg = newMpg;
    }
    
  4. In main(), construct an object using the overloaded constructor and then call print() as follows:
    cout << "Other cars for comparison:\n";
    Car corolla("Toyota Corolla", 25000, 34);
    corolla.print();
    
  5. Compile and run your program and verify you see the car information printed like:
    none @ 0 with MPG 0
    Enter the name of the car: Tesla 3
    Enter the price for a Tesla 3: 35000
    Enter the MPG for a Tesla 3: 134
    Tesla 3 @ 35000 with MPG 134
    Other cars for comparison:
    Toyota Corolla @ 25000 with MPG 34
    

    User input is shown in aqua italics for the example only, NOT in your program. If you have problems, ask a classmate or the instructor for help.

  6. Identify which constructor is called for each object and add a comment in your source code where the object is created.
  7. Once satisfied with your code, copy your code into a text editor, save the file as "multictor.cpp", and submit the file to Canvas with the rest of the exercise files for the week.

When finished developing your code click hereClick to show answer to verify. Code need not look exactly the same. After you have completed your own program, reviewing another is often helpful in learning how to improve your programming skills.

11.7: Vectors of Objects

Reviewing Vectors of Objects

Example Vector of Objects

#include <iostream>
#include <vector>
using namespace std;

class Product {
public:
    Product();
    Product(string newName, double newPrice);
    void print() const;
private:
    string name;
    double price;
};

Product::Product() {
    name = "Unknown";
    price = 0.0;
}

Product::Product(string newName, double newPrice) {
    name = newName;
    price = newPrice;
}

void Product::print() const {
    cout <<  name << " @ " << price << endl;
}

int main() {
    const int SIZE = 3;
    vector<Product> list(SIZE);
    list.at(0) = Product("Milk", 3.95);
    list.at(1) = Product("Bread", 2.99);
    list.at(2) = Product("Cheese", 3.95);

    cout << "Products in my store:\n";
    for (unsigned i = 0; i < list.size(); i++) {
        list.at(i).print();
    }

    return 0;
}

Adding Items to a Vector of Objects

Example Vector of Objects

#include <iostream>
#include <vector>
using namespace std;

class Product {
public:
    Product();
    Product(string newName, double newPrice);
    void read();
    void print() const;
private:
    string name;
    double price;
};

Product::Product() {
    name = "Unknown";
    price = 0.0;
}

Product::Product(string newName, double newPrice) {
    name = newName;
    price = newPrice;
}

void Product::read() {
    cout << "Enter the name of the product: ";
    cin >> ws;
    getline(cin, name);
    cout << "Enter the price for a " << name << ": ";
    cin >> price;
}

void Product::print() const {
    cout <<  name << " @ " << price << endl;
}

void addProduct(vector<Product>& store); // function prototype

void listProducts(vector<Product>& store); // function prototype

int main() {
    const int SIZE = 3;
    vector<Product> myStore(SIZE);  // vector of Product objects
    myStore.at(0) = Product("Milk", 3.95); // add objects to vector
    myStore.at(1) = Product("Bread", 2.99);
    myStore.at(2) = Product("Cheese", 3.95);
    int choice = 1;
    while (choice != 0) {
        cout << "\n0. Exit program\n"
             << "1. Report inventory\n"
             << "2. Add a new product\n"
             << "Choice (0-2): ";
        cin >> choice;
        if (choice == 1) {
            listProducts(myStore);    // call non-member function
        } else if (choice == 2) {
            addProduct(myStore);      // call non-member function
        } else if (choice != 0) {
            cout << "\nInvalid choice!\n";
        }
    }
    cout << "\nGoodbye!\n";
    return 0;
}

void addProduct(vector<Product>& store) { // function definition
    cout << "\nAdding a new product:\n";
    Product prod;               // construct an object
    prod.read();                // call member function read()
    store.push_back(prod);      // copy object onto vector
}

void listProducts(vector<Product>& store) {
    cout << "\nListing products:\n";
    for (unsigned num = 0; num < store.size(); num++) {
        cout << (num + 1) << " ";
        store[num].print();     // call member function print()
    }
}

Member vs. Non-member Functions

CA 11.7: Challenge activities

Any problems with any of these Challenge activities? (Zybooks sign in)

If so, list the CA numbers in Chat

Exercise 11.7: Coding Vectors of Objects (18m)

In this exercise we explore how to add items to and list items of a vector of objects.

For this exercise we break into teams. Within the team, work with each other to develop a solution. When the team has finished, choose one member to show your solution to the class by sharing your screen. The instructor will ask one team to share their solution.

Specifications

  1. Start Repl.it and copy the following code into the code editor.
    #include <iostream>
    #include <vector>
    using namespace std;
    
    class Car {
        public:
        Car();
        Car(string newName, double newPrice, double newMpg);
        void read();
        void print() const;
    
        private:
        string name;
        double price;
        double mpg;
    };
    
    Car::Car() {
        name = "none";
        price = 0.0;
        mpg = 0.0;
    }
    
    Car::Car(string newName, double newPrice, double newMpg) {
        name = newName;
        price = newPrice;
        mpg = newMpg;
    }
    
    void Car::read() {
        cout << "Enter the name of the car: ";
        cin >> ws;
        getline(cin, name);
        cout << "Enter the price for a " << name << ": ";
        cin >> price;
        cout << "Enter the MPG for a " << name << ": ";
        cin >> mpg;
    }
    
    void Car::print() const {
        cout << name << " @ " << price << " with MPG " << mpg << endl;
    }
    
    int main() {
        Car myCar("Tesla", 35000, 134);
        myCar.print();
    
        return 0;
    }
    
  2. In main() after constructing the myCar object, construct a vector of Car objects named list with a size of one (1). Add the myCar object to list at element zero (0) and then print element zero. When finished main() should look like the following:
    int main() {
        Car myCar("Tesla", 35000, 134);
        vector<Car> list(1);
        list.at(0) = myCar;
        list.at(0).print();
    
        return 0;
    }
    

    Continue to compile and run after each step to test your code.

  3. Above the main() function, add the following function definition:
    void listCars(vector<Car>& list) {
        cout << "\nListing cars:\n";
        for (unsigned num = 0; num < list.size(); num++) {
            cout << (num + 1) << " ";
            list[num].print(); // call print() in Car
        }
    }
    
  4. In the main() function, call the listCars() function, replacing the call to print(). When finished main() should look like the following:
    int main() {
        Car myCar("Tesla", 35000, 134);
        vector<Car> list(1);
        list.at(0) = myCar;
        listCars(list);
    
        return 0;
    }
    

    Note that the listCars() function is calling the print() member function of Car.

  5. Above the main() function, add the following function definition:
    void addCar(vector<Car>& list) { // function definition
        cout << "\nAdding a new car:\n";
        Car aCar;               // construct an object
        aCar.read();            // call member function read()
        list.push_back(aCar);   // copy object onto vector
    }
    
  6. In the main() function, call the addCar() function and then call listCars() again. When finished main() should look like the following:
    int main() {
        Car myCar("Tesla", 35000, 134);
        vector<Car> list(1);
        list.at(0) = myCar;
        addCar(list);
        listCars(list);
    
        return 0;
    }
    

    Note that the addCar() function is calling the read() member function of Car.

  7. Compile and run your modified program to make sure you made the changes correctly. When running the program, the output should look like:
    Listing cars:
    1 Tesla @ 35000 with MPG 134
    
    Adding a new car:
    Enter the name of the car: Toyota Corolla
    Enter the price for a Toyota Corolla: 25000
    Enter the MPG for a Toyota Corolla: 34
    
    Listing cars:
    1 Tesla @ 35000 with MPG 134
    2 Toyota Corolla @ 25000 with MPG 34
    

    In the above example run, the user entered the values shown in aqua italics (for emphasis) in a terminal window to produce the output. Your program does NOT print the characters in aqua italics, nor does the user input appear in aqua italics.

  8. Now we want to create a short menu to call our functions. Replace the following sequence of three function calls in main()
    listCars(list);
    addCar(list);
    listCars(list);
    
    with the following code:
    int choice = 1;
    while (choice != 0) {
        cout << "\n0. Exit program\n"
             << "1. Report inventory\n"
             << "2. Add a new car\n"
             << "Choice (0-2): ";
        cin >> choice;
        if (choice == 1) {
            listCars(list);
        } else if (choice == 2) {
            addCar(list);
        } else if (choice != 0) {
            cout << "\nInvalid choice!\n";
        }
    }
    cout << "\nGoodbye!\n";
    
  9. Compile and run your modified program to make sure you made the changes correctly. When running the program, the menu output should look like:
    0. Exit program
    1. Report inventory
    2. Add a new car
    Choice (0-2):
    

    Also, you should be able to add and list products as often as you like.

  10. Once satisfied with your code, copy your code into a text editor, save the file as "carlist.cpp", and submit the file to Canvas with the rest of the exercise files for the week.

When finished developing your code click hereClick to show answer to verify. Code need not look exactly the same. After you have completed your own program, reviewing another is often helpful in learning how to improve your programming skills.