An Object-Oriented Implementation Using C++
Object-oriented languages really gained momentum in the late 1990s, but they've been around for a lot longer. Smalltalk and C++ are good examples. Whereas Smalltalk is considered a pure object-oriented language, C++ is actually an object-based language. This distinction exists because Smalltalk enforces object-oriented concepts and C++ doesn't. This point is important because modern object-oriented languages do enforce object-oriented concepts (at least mostly).
C++ is a powerful programming language that was developed to be backwardly compatible with C. You can design and implement object-oriented code in C++, but you can also use a C++ compiler to write straight C code (which is obviously not object-oriented). I've interviewed many people who insist that they're C++ programmers, but in fact they're simply using a C++ compiler to write C code.
Working from the original application in Listing 1, let's design an object-oriented implementation in C++ (by designing a class). We might as well just jump right in to see what the accessor methods would look like. In this case, the setter is setAge() and the getter is getAge(). The code is in Listing 3.
Listing 3C++ implementation designed with a class.
// CPPLicense01.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <stdio.h> #include <iostream> // License.h // class License { private: int age; public: void setAge(int); int getAge(); }; int main() { License joe; joe.setAge(16); printf("age = %d\n", joe.getAge()); system("pause"); return 0; } // License.cpp // #include "stdafx.h" #include <stdio.h> void License::setAge(int a) { age = a; } int License::getAge() { return (age); }
In this design, you can see immediately that the data and the code are defined (encapsulated) in a single class called License—a true expression of encapsulation. Also, as is normally the case, the data is declared as private and the methods as public. Thus, the attribute, age, has private access, while the methods, setAge() and getAge(), have public access.
This practice illustrates one of my primary object-oriented design guidelines: When you design an application, initially make all attributes private. This practice is sound because the default access for all data will be private.
The syntax of accessor methods sheds a lot of light on the direction that data access has evolved. We once used the equal sign (=) to set variables, as in this line of code from our previous C program:
age = 16;
Now we use methods to set the data values, as in this line from the OO approach:
joe.setAge(16);
Later we'll see how the pendulum may be starting to swing back in the direction of the equal sign.