Lecture Preview: Classes and Objects

(Suggested book reading: Programming Abstractions in C++, Chapter 6)

Today we will start to talk about classes and objects. A class is a program entity that represents a template for a new type of objects. An object is an entity that combines state and behavior. Objects are powerful reusable software components that make it easier to write large applications. Object-oriented programming ("OOP") means writing programs that perform a large part of their behavior as interactions between objects.

A class is like a blueprint that describes how to create objects, as shown in the following figure.

figure

When you write a new class Foo in C++, you must write two files:

  1. Foo.h: A "header" file containing only the class's interface (declarations of all of its variables and methods). In this file, you declare everything with semicolons, almost like declaring function prototypes at the top of a .cpp file earlier in this course, but you don't write in the actual bodies of the methods with {}.
  2. Foo.cpp: A "source" file containing definitions of the bodies of all of the methods declared in the .h file. In this file, you write the actual method bodies in {}.

Recall that a class often consists of the following elements. (This should be a review from CS 106A or your equivalent course.)

  • fields (member variables): The data inside each object.
  • methods (member functions): The behavior each object can execute, using the data from its fields.
  • constructor: Initializes the state of each newly created object.

Here is an example of a file named Date.h that declares a new class named Date:

/* Date.h */
#ifndef _date_h
#define _date_h

class Date {
public:
    Date(int m, int d);   // constructor
    
    int daysInMonth();    // member functions (aka methods)
    int getMonth();
    int getDay();
    void nextDay();
    string toString();

private:
    int month;            // member variables (fields)
    int day;
};

#endif

Here is an example of (the partial contents of) a file named Date.cpp that defines the bodies of the members declared in Date.h:

/* Date.cpp */
#include "Date.h"

Date::Date(int m, int d) {           // constructor
    month = m;
    day = d;
}

int Date::getMonth() {               // member functions
    return month;
}

string Date::toString() {
    return integerToString(month) + "/" + integerToString(day);
}
...
This document and its content are copyright © Marty Stepp, 2015. All rights reserved. Any redistribution, reproduction, transmission, or storage of part or all of the contents in any form is prohibited without the authors' expressed written permission.