CS 1440 Lab 8

Cover sheetPrevious ActivityNext Activity

Activity 8-4: Header and Implementation Files

Activity Goals

        Knowing what goes in a class header file.

        Knowing what goes in class implementation file.

        Knowing how to use class and implementation files for our programs.

Activity Procedure

In activity 3 you used the Date class.  You had to cut and paste it into the new Act3.C program file.  Do we always have to cut and paste classes to use them in different places?  Of course not!

Instead, we typically write the class definition in a class header file.  The class function definitions go into a class implementation file.  Then the client program file just does #include to get access to the class definition.  One last, and important, thing though.  When we compile, we must somehow compile the client program code AND the class implementation code TOGETHER.  This is easily done by compiling both files together like: 

          g++  file1.C  file2.C


So, activity 2 used a Date class and the Act2.C program file (the main function).  This is how we would do it with header and implementation files:

Date Header

Date Implementation

Program File

#ifndef DATE_H
#define DATE_H

class  Date
   void set(int m, int d, int y);
   void LongDisplay();
   void ShortDisplay();
   int day, month, year;


#include <iostream>
#include "Date.h"

void Date::set(int m, int d, int y)
   /* Set  “my”  data members with
     values passed in from client
     as parameters. */
   year  =  y;
   day  =  d;
   month  =  m;
void  Date::ShortDisplay()
   /* Display as: mm/dd/yyyy
      for example: 3/31/2002 */

   cout  <<  month  <<  "/"
         <<  day    <<  "/"
         <<  year;
void  Date::LongDisplay()
  /* Display as:  dd Month yyyy
     for example:  31 March 2002 */

       /*  YOU DO IT!! */

#include <iostream>
#include "Date.h"

int  main()
   Date  today;
   int  d, m, y;

   cout  <<  "Enter month: ";
   cin  >>  m;
   cout  <<  "Enter day: ";
   cin  >>  d;
   cout  <<  "Enter year: ";
   cin  >>  y;

   cout  <<  endl;
   cout  <<  endl;

   return 0;

Notice in Act4.C that including one of your own header files is done a little differently.  You use " instead of < around the file.  Also notice that Date.C now needs to include Date.h too!

So, to compile this program (since there are now multiple files) we would give the following command:
            g++  Date.C  Act4.C

Activity Followup

            Start using class header and implementation files in your programs.