Core C++

Lesson 51 : Header and Source Files

In this C++ video tutorial, we demonstrate how to break code out into header and source files. Breaking code into smaller pieces like this makes the code more modular, which allows for code reuse and aids in organization. In larger projects, which consist of numerous code files, organization and reuse are necessary to get the work done and prevent bugs.

Below, we give the code that demonstrates the usage of a simple light class that is broken into three files. The file "main.cpp" instantiates a CLight object and calls the function IsOn() several times to report whether or not the light is on. In between calls, we call FlipSwitch() twice to turn the light on and then off. At the top of "main.cpp," we included the header "CLight.h" so that we can use the class.

// main.cpp
#include <iostream>
#include "CLight.h"

int main() {
    using namespace std;

    CLight qMyLight;

    cout << "The Light " <<
        (qMyLight.IsOn() ? "is" : "is not") << " on."<< endl;
    qMyLight.FlipSwitch();
    cout << "The Light " <<
        (qMyLight.IsOn() ? "is" : "is not") << " on."<< endl;
    qMyLight.FlipSwitch();
    cout << "The Light " <<
        (qMyLight.IsOn() ? "is" : "is not") << " on."<< endl;

    return 0;
}

Below, we have the header file "CLight.h", which contains our class definition. This class definition contains a boolean to indicate whether or not the light is on and two member functions: FlipSwitch() and IsOn(). Around the definition, we have placed a macro guard to guard against multiple inclusions. The macro guard is made up of preprocessor directives, which we covered in C++ Console Lesson 37. If you are using Visual C++, you can see our video on how to add headers files for more information.

// CLight.h
#ifndef CLIGHT_H
#define CLIGHT_H

class CLight
{
public:
    CLight();
    ~CLight();
    void FlipSwitch();
    bool IsOn();
private:
    bool mbIsOn;
};

#endif

Below, we have the source file "CLight.cp", which contains our implementation. This constructor initializes the bool with false, while FlipSwitch() toggles the boolean value and IsOn() returns it. Just as we did in "main.cpp", we include the header file at the beginning. If you are using Visual C++, you can see our video on how to add source files for more information.

// CLight.cpp
#include "CLight.h"

CLight::CLight() : mbIsOn(false) {}

CLight::~CLight() {}

void CLight::FlipSwitch() {
    mbIsOn = !mbIsOn;
}

bool CLight::IsOn() {
    return mbIsOn;
}

Executing the program by pressing (Ctrl + F5), gives the output shown below.

 

© 2007–2024 XoaX.net LLC. All rights reserved.