(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:
const int x = 4; // x will always be 4
void foo(const Date& d) { ... // foo won't change d
class Date {
...
int getDay() const; // getDay won't change date