20-CS-122-001 Computer Science II Spring 2012
Split a C++ Class into .h and .cc files

Virtual functions, classes, inheritance, lists, queues, stacks, applications

Source

Consider the following class file:

  #include <iostream>
  using namespace std;

  class Tester {
     int n, *group;

   public: 
     Tester (int n) {
        this->n = n;
        group = new int[n];
        for (int i=0 ; i < n ; i++) group[i] = n-i;
     }

     void print () {
        for (int i=0 ; i < n ; i++) cout << group[i] << " ";
        cout << "\n";
     }

     int find (int k) {
        for (int i=0 ; i < n ; i++) if (group[i] == k) return i;
        return -1;
     }
  };
Put copies of the above class into .h and .cc files whose names share the same prefix which is related to the name of the class. For example, in the case of class Tester the file names might be tester.h and tester.cc. In tester.h place all the includes needed by the class, and prototype the entire class, leaving in all class data declarations, but omitting the implementation of the methods, constructor, destructor, and names of arguments. Also, test for and define a constant object at the beginning of the file that will be used to prevent the include file from being loaded twice. The file tester.h for the class Tester is:
  #ifndef _TESTER
  #define _TESTER
  #include <iostream>
  using namespace std;

  class Tester {
     int n, *group;

   public: 
     Tester (int);
     void print ();
     int find (int);
  };
  #endif
In tester.cc implement the methods, constructor, and destructor of the class. Before the name of each, add the name of the class followed by two colons. Include the corresponding include file. Write tester.cc as follows:
  #include "tester.h"

  Tester::Tester (int n) {
     this->n = n;
     group = new int[n];
     for (int i=0 ; i < n ; i++) group[i] = n-i;
  }

  void Tester::print () {
     for (int i=0 ; i < n ; i++) cout << group[i] << " ";
     cout << "\n";
  }

  int Tester::find (int k) {
     for (int i=0 ; i < n ; i++) if (group[i] == k) return i;
     return -1;
  }
Compile this to object code using g++ as follows:
  g++ -c tester.cc
This results in an object file called tester.o. This file may be linked with others to create an executable piece of code. For example, create file main.cc with the following contents:
  #include "tester.h"

  int main () {
     Tester *tester = new Tester(100);
     tester->print();
     cout << tester->find(4) << "\n";
  }
Compile it as follows:
  g++ -c main.cc
Then link all the files as follows:
  g++ main.o tester.o -o main
This creates the executable file called main. Run main as follows:
  prompt> ./main
  100 99 98 97 96 95 94 93 92 91 90 89 88 87 86 85 84 83 82 81 80 79 78 77 76 75 74
  73 72 71 70 69 68 67 66 65 64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 
  46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20
  19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
  96