Lecture Preview: Classes and Objects 2

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

Today we will discuss more about classes and objects. One interesting feature in C++ is called operator overloading, which makes it possible to use your new class with existing operators like +, ==, or <. The general syntax for overloading an operator is the following:

returnType operator op(parameters);      // .h
returnType operator op(parameters) {     // .cpp
    statements;
};

Here is an example of an == operator for comparing Date objects for equality:

/* Date.h */
class Date {
   ...
};

bool operator ==(Date& d1, Date& d2);
/* Date.cpp */
bool operator ==(Date& d1, Date& d2) {
    return d1.getMonth() == d2.getMonth() && d1.getDay() == d2.getDay();
}

Another feature of classes we will talk about today is the keyword const. The C++ const keyword indicates that a value cannot change. You can use it in several ways:

  1. On any variable, to indicate that this variable's value will never be changed from its initial value.
    const int x = 4;                // x will always be 4
  2. On a reference parameter, to ensure that this parameter's value can't be modified by the function (making it an "input-only" parameter).
    void foo(const Date& d) { ...   // foo won't change d
  3. At the end of an object's member function, to ensure that calling this function won't change the object's state:
    class Date {
        ...
        int getDay() const;         // getDay won't change date
    
This document and its content are copyright © Marty Stepp, 2018. 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.