C++ Separate Header and Implementation Files Example
C++ Separate Header and Implementation Files Example
Header File
Class declarations are stored in a separate file. A file that contains a class declaration is called header file. The name of the class is
usually the same as the name of the class, with a .h extension. For example, the Time class would be declared in the file Time .h.
#ifndef TIME_H
#define TIME_H
class Time
{
private :
int hour;
int minute;
int second;
public :
//with default value
Time(const int h = 0, const int m = 0, const int s = 0);
// setter function
void setTime(const int h, const int m, const int s);
// Print a description of object in " hh:mm:ss"
void print() const;
//compare two time object
bool equals(const Time&);
};
#endif
Implementation File
The member function definitions for a class are stored in a separate .cpp file, which is called the class implementation file. The file usually
has the same name as the class, with the .cpp extension. For example the Time class member functions would be defined in the file
Time.cpp.
www.cppforschool.com/tutorial/separate-header-and-implementation-files.html 1/3
11/13/23, 7:53 PM C++ Separate Header and Implementation Files Example
#include <iostream>
#include <iomanip>
#include "Time.h"
using namespace std;
Client Code
client code, is the one that includes the main function. This file should be stored by the name main.cpp
#include <iostream>
using namespace std;
#include "Time.h"
int main()
{
Time t1(10, 50, 59);
t1.print(); // 10:50:59
Time t2;
t2.print(); // 06:39:09
t2.setTime(6, 39, 9);
t2.print(); // 06:39:09
if(t1.equals(t2))
cout << "Two objects are equal\n";
else
cout << "Two objects are not equal\n";
return 0;
}
2. The clients of the class know what member functions the class provides, how to call them and what return types to expect
3. The clients do not know how the class's member functions are implemented.
www.cppforschool.com/tutorial/separate-header-and-implementation-files.html 2/3
11/13/23, 7:53 PM C++ Separate Header and Implementation Files Example
www.cppforschool.com/tutorial/separate-header-and-implementation-files.html 3/3