The key to managing this is to clearly define the interactions among those parts. The first and most important step is to distinguish between the interface to a part and its implementation. At the language level, C++ represents interfaces by declarations. A declaration specifies all that’s needed to use a function or a type. For example:
- double sqrt(double); // a square root function that takes arguments of type double and returns a variable of type double
- // Declaring a class with all the necessary methods and class members
- class Vector
- {
- public:
- Vector(int s);
- double& operator[](int i);
- int size();
- private:
- double∗ elem;
- int sz;
- };
The key point here is that the implementation of all methods and functions can be in a completely different place, in another file. Often, functions are declared in header files with the extension .h , and the implementation is performed in the source code files .cpp .
For example, the implementation of the square root function:
- double sqrt(double d) // definition of sqrt()
- {
- // ... algorithm as found in math textbook ...
- }
Also, for the Vector class, several participants will need to be implemented:
- Vector::Vector(int s) // definition of the constructor
- : elem{new double[s]}, sz{s} // initialization of participants
- {
- }
- double& Vector::operator[](int i) // definition of an access operator
- {
- return elem[i];
- }
- int Vector::size() // definition method size ()
- {
- return sz;
- }
We must define Vector’s functions, but not sqrt() because it is part of the standard library. However, that makes no real difference: a library is simply some ‘‘other code we happen to use’’ written with the same language facilities as we use.