3 File Structure

When creating a class, it is recommended to use the so-called "3 file structure".  We specify the class interfaces in the .h file and implement the class functions in the .cpp file, such as time.h and time.cpp in the other example.  The third file is the test file which contains the main() program.  In our example, it is called main.cpp, but it can be called anything as long as compiler can find main() routine in it.

Why 3 files?

Well, for one thing, it separates interface specification from implementation such that the class factory (owner) can change/improve class implementation without bothering the clients programs.  When main.cpp (shown below) is compiled, it includes the interfaces #include "time.h", but not the implementations.

#include <iostream>

using namespace std;

#include "Time.h"

int main()

{

   Time t(3,4); // create Time object

   Time t2(3);

   // display current time

   cout << "The universal time is ";

   t2.printUniversal();

   cout << "\nThe standard time is ";

   t.printStandard();

   cout << endl;

   return 0;

} // end main

When compiler encounters Time t(3,4);  it needs to know what is Time.  That's the reason we need to tell compiler to include the specification.  Similarly, when time.cpp file is compiled, the compiler also needs to know what is Time.  So, time.cpp needs to have the same #include as well.

What is that #ifndef thing in every .h file?

Compiler replaces #include "Time.h"  by copying entire Time.h file in its place.  So, when we compile main.cpp and IF encounter more than one #include "Time.h" , then two copies of time class will be specified.  The result is a "duplicate definition" compiler error.  It won't have error if there is only one definition.

To avoid multiple definition issue, it is customary to use #define xxx_H   with each definition .h file, such as

#ifndef    TIME_H

#define    TIME_H

class Time 

{

public:

   void printTime();

   int hour; 

   int minute;

   int second;

}; // end class Time

#endif