After not having used it for a couple of decades, I had to dive back into C++ for a project. I hadn’t used “include” files in a long time and needed to refresh my understanding of how they, and the compiler and linker, worked. To do that, I wrote a quick example to make sure I still understood.

My example defines only one class and then exercises that class in a simple main() function. The class has all of: a constructor; a destructor; a public method; a public variable; and a protected variable. Because I also wanted to use more than one source file and use an include file too, the code is separated into three files.

First, the class is declared in an “include” file. Declaring a class merely states, in a way, what the class can do and how a program which uses it can interact with it. A pure declaration doesn’t actually implement any logic. The actual implementation is called the “definition” or “defining the class”. I defined the methodsĀ  of my class in a separate file. Lastly, I created a third file which referred to the include file and the class definition file, in order to exercise them.

The include file, test_class.h

#ifndef _TEST_CLASS_H
#define _TEST_CLASS_H

	class TestClass {
	    public:

	    TestClass(int protectedVar);
            ~TestClass();

	    void testFunc();

	    int publicVar;

	    protected:

	    int protectedVar;

	};

#endif // _TEST_CLASS_H

Next, the definition of the methods in the class, in TestClass.cc

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

	    TestClass::TestClass(int protectedVarArg) {
	        std::cout << "TestClass constructor" << std::endl;
                publicVar = 3;
                protectedVar = protectedVarArg;

	        return;
	    }

	    TestClass::~TestClass() {
	        std::cout << "TestClass destructor" << std::endl;

	        return;
	    }

	    void TestClass::testFunc() {
	        std::cout << "In testFunc()" << std::endl;
	        std::cout << " protectedVar " << protectedVar << std::endl;

	        return;
	    }

And, finally, the main function, in classTest.cc

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

int
main(int numberOfArguments,
     char* arrayOfArguments[]) {

    TestClass testClass(5);

    std::cout << "testClass.publicVar: " << testClass.publicVar << std::endl;

    testClass.testFunc();

    return 0;
};

On a Linux system using the Gnu C++ suite, these three files can be compiled and linked into a binary executable with:

g++ -o classTest classTest.cc TestClass.cc
Advertisements