Introduction to C++ Classes


Contents


An Example C++ Class

C++ classes are similar to Java classes in many ways, but there are also important differences. Below is an example of a C++ class named IntList to be used to represent a list of integers; operations to add a value to the end of the list and to print the list are provided. The implementation uses a dynamically allocated array to store the integers; when the array is full, a new array of twice the size is allocated.

In Java, the class definition would all be in a single file. However, in C++ the code that defines the class would be split into two files: the first part specifies what member functions (methods) and data members (fields) the class will have. That code goes into a header file: a file with the extension .h. It is usually a good idea (though not a requirement as in Java) to give the file the same name as the class (so the file would be named IntList.h).

The second part of the class definition gives the code for the function bodies. That code goes in a source file (e.g., IntList.C).

The reason for splitting up the code is that it is generally a good idea to try to separate the interface from the implementation. Someone who wants to use an IntList really only needs to know what IntList operations are available; it is not necessary to know all the details about how an IntList is implemented. However, splitting up the code in this way is not required by C++. Some people prefer to include code for the member functions in the .h file when that code involves only one or two statements.

Here is the code that would be in IntList.h:

Things to note about the example so far: Here is the code that would be in IntList.C (the actual code for the AddToEnd and Print functions has been omitted): Things to note about this part of the example:

Constructor Functions

As in Java, constructor functions can be overloaded (there can be multiple constructors for a class, as long as each has a different number and/or type of parameters). In C++, a constructor function is called either when a class object is declared:

or when the object is dynamically allocated:

To use a constructor with parameters, just put the values for the parameters in parentheses as follows:


TEST YOURSELF NOW

  1. Extend the IntList class defined above by adding a member function called Length. The function should return the number of items currently in the list. Write the new declaration that would be added to IntList.h as well as the new code that would be added to IntList.C (write the complete code for the new function , not just ... as in the example).

  2. Add a 2-argument constructor to the IntList class to allow an IntList to be initialized to contain n copies of value v. (So the two arguments are n and v, both of type int.) Again, write both the new declaration that would be added to IntList.h, and the new code that would be added to IntList.C.

solution


Two Useful Standard Classes: string and vector

The string class

To use the string class you must #include <string> (be sure that you do not include string.h, because then you will get the header file for C-style strings rather than for the C++ string class).

More detailed documentation on strings is available: click here.

The vector class

To use the vector class you must #include <vector>. A vector is similar to an array, but vectors provide some operations that cannot be performed using C++ arrays, and vectors can be passed both by value and by reference (unlike C++ arrays, which are always passed by reference). Unfortunately, there is no bounds checking for vectors (i.e., an index out of bounds does not necessarily cause a runtime error).


TEST YOURSELF NOW

  1. Write a function named NonEmpty that has one parameter, a vector of strings V, and that returns another vector of strings that contains just the non-empty strings in V. For example, if parameter V contains the 6 strings: then function NonEmpty should create and return a vector that contains the 3 strings:

  2. Write a function named Expand that has one parameter, a vector of ints V. Expand should change V so that it is double its original size, and contains (in its first half) the values that were originally in V.

    Test your function with the following main function:

    When you run this program, the output should be:

solution


Solutions to Self-Study Questions

Test Yourself #1

Question 1:

To extend the IntList class to include member function Length, the following would be added to the public part of the class declaration (in the file IntList.h):

Note that Length should be a const member function because it does not modify any fields.

The code for the Length function (to be added to the file IntList.C) is:

Question 2:

To extend the IntList class by adding a 2-argument constructor, the following would be added to the public part of the class declaration:

and the following would be added to IntList.C: Note that this version of the 2-argument constructor first initializes the list to be empty (by setting numItems to zero), then uses the AddToEnd function to add value v to the list n times. Of course, the code that stores v in the Items array could be included here instead of calling AddToEnd; however, it is usually better to call a function than to duplicate code.

Test Yourself #2

Question 1:

Note that this solution make two passes through vector V: the first pass counts the number of non-empty strings in vector V, and the second pass fills in the new vector newV (after it has been declared to have the appropriate size). An alternative would be to start by defining newV to have size 0, and make a single pass through vector V, resizing newV by 1 each time another non-empty string is found in V. The problem with that approach is that resizing a vector from size n to size n+1 probably takes time O(n) (to copy the values). (The actual time depends on the implementation of resize; a straightforward implementation that allocates exactly the amount of memory requested will be O(n).) Therefore, the alternative approach would be O(n2), while the solution given above is O(n), where n is the number of non-empty strings in vector V.

Question 2:

Note that it is crucial to make Expand's parameter a reference parameter.