(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.
When you write a new class Foo
in C++, you must write two files:
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 {}.
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.)
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); } ...