Wednesday, May 5, 2010

class

The class is the C++ construct for encapsulation. Encapsulation means publishing an interface through which you make things happen, and hiding the implementation and data necessary to do the job. A class is used to hide data, and publish operations on the data, at the same time. Let's look at the "Range" example from last month, but this time make it a class. The only operation that we allowed on the range last month was that of construction, and we left the data visible for anyone to use or abuse. What operations do we want to allow for a Range class? I decide that 4 operations are desirable:
Construction (same as last month.)
find lower bound.
find upper bound.
ask if a value is within the range. The second thing to ask when wishing for a function is (the first thing being what it's supposed to do) is in what ways things can go wrong when calling them, and what to do when that happens. For the questions, I don't see how anything can go wrong, so it's easy. We promise that the functions will not throw C++ exceptions by writing an empty exception specifier.
I'll explain this class by simply writing the public interface of it:
struct BoundsError {};
class Range
{
public:
Range(int upper_bound = 0, int lower_bound = 0)
throw (BoundsError);
// Precondition: upper_bound >= lower_bound
// Postconditions:
// lower == upper_bound
// upper == upper_bound
int lowerBound() throw ();
int upperBound() throw ();
int includes(int aValue) throw ();
private:
// implementation details.
};
This means that a class named "Range" is declared to have a constructor, behaving exactly like the constructor for the "Range" struct from last month, and three member functions (also often called methods,) called "lowerBound", "upperBound" and "includes". The keyword "public," on the fourth line from the top, tells that the constructor and the three member functions are reachable by anyone using instances of the Range class. The keyword "private" on the 3rd line from the bottom, says that whatever comes after is a secret to anyone but the "Range" class itself. We'll soon see more of that, but first an example (ignoring error handling) of how to use the "Range" class:
int main(void)
{
Range r(5);
cout << "r is a range from " << r.lowerBound() << " to "
<< r.upperBound() << endl;
int i;
for (;;)
{
cout << "Enter a value (0 to stop) :";
cin >> i;
if (i == 0)
break;
cout << endl << i << " is " << "with"
<< (r.includes(i) ? "in" : "out") << " the range"
<< endl;
}
return 0;
}
A test drive might look like this:
[d:\cppintro\lesson2]rexample.exe
r is a range from 0 to 5
Enter a value (0 to stop) :5
5 is within the range
Enter a value (0 to stop) :7
7 is without the range
Enter a value (0 to stop) :3
3 is within the range
Enter a value (0 to stop) :2
2 is within the range
Enter a value (0 to stop) :1
1 is within the range
Enter a value (0 to stop) :0
Does this seem understandable? The member functions "lowerBound", "upperBound" and "includes" are, and behave just like, functions, that in some way are tied to instances of the class Range. You refer to them, just like you do member variables in a struct, but since they're functions, you call them (by using the, in C++ lingo named, function call operator "()".)
Now to look at the magic making this happen by filling in the private part, and writing the implementation:
struct BoundsError {};
class Range
{
public:
Range(int upper_bound = 0, int lower_bound = 0)
throw (BoundsError);
// Precondition: upper_bound >= lower_bound
// Postconditions:
// lower == upper_bound
// upper == upper_bound
int lowerBound() throw ();
int upperBound() throw ();
int includes(int aValue) throw ();
private:
int lower;
int upper;
};
Range::Range(int upper_bound, int lower_bound)
throw (BoundsError)
: lower(lower_bound), /***/
upper(upper_bound) /***/
{
// Preconditions.
if (upper_bound < lower_bound) throw BoundsError();
// Postconditions.
if (lower != lower_bound) throw BoundsError();
if (upper != upper_bound) throw BoundsError();
}
int Range::lowerBound() throw ()
{
return lower; /***/
}
int Range::upperBound() throw ()
{
return upper; /***/
}
int Range::includes(int aValue) throw ()
{
return aValue >= lower && aValue <= upper; /***/
}
First, you see that the constructor is identical to that of the struct from last month. This is no coincidence. It does the same thing and constructors are constructors. You also see that "lowerBound", "upperBound" and "includes", look just like normal functions, except for the "Range::" thing. It's the "Range::" that ties the function to the class called Range, just like it is for the constructor.
The lines marked /***/ are a bit special. They make use of the member variables "lower_bound" and "upper_bound." How does this work? To begin with, the member functions are tied to instances of the class, you cannot call any of these member functions without having an instance to call them on, and the member functions uses the member variables of that instance. Say for example we use two Range instances, like this:
Range r1(5,2);
Range r2(20,10);
Then r1.lowerBound() is 2, r1.upperBound() is 5, r2.lowerBound() is 10 and r2.upperBound() is 20.
So how come the member functions are allowed to use the member data, when it's declared private? Private, in C++, means secret for anyone except whatever belongs to the class itself. In this case, it means it's secret to anyone using the class, but the member functions belong to the class, so they can use it.
So, where is the advantage of doing this, compared to the struct from last month? Hiding data is always a good thing. For example, if we, for whatever reason, find out that it's cleverer to represent ranges as the lower bound, plus the number of valid values between the lower bound and upper bound, we can do this, without anyone knowing or suffering from it. All we do is to change the private section of the class to:
private:
int lower_bound;
int nrOfValues;
And the implementation of the constructor to:
Range::Range(int upper_bound, int lower_bound)
throw (BoundsError)
: lower(lower_bound), /***/
nrOfValues(upper_bound-lower_bound) /***/
...
And finally the implementations of "upperBound" and "includes" to:
int Range::upperBound() throw ()
{
return lower+nrOfValues;
}
int Range::includes(int aValue) throw ()
{
return aValue >= lower && aValue <= lower+nrOfValues;
}
We also have another, and usually more important, benefit; a promise of integrity. Already with the struct, there was a promise that the member variable "upper" would have a value greater than or equal to that of the member variable "lower". How much was that promise worth with the struct? This much:
Range r(5, 2);
r.lower = 25; // Oops! Now r.lower > r.upper!!!
Try this with the class. It won't work. The only one allowed to make changes to the member variables are functions belonging to the class, and those we can control.

No comments:

Post a Comment