Using header files in C++ .NET

Using header files in C++ .NET
This tutorial will show you how to work with C++ .NET headers (or includes). How to create a header file with a class in it, include the file in a typical .cpp file, set a variable and call a public function, both defined inside the header.

So let’s see how it’s done. Create a new C++ Console Application project named OrganizedClass in Visual Studio .NET.

Now, in the Solution Explorer look for the folder Header Files. Right click it, choose Add -> Add New Item and from the window that appears choose Header File (.h). For the name you can go with MyHeader.

The MyHeader.h is created and opened in the editor.

Open it and inside we shall use the following code:

// The name of the class

class MyClass



   // One public member function

   void SomeFunction();

   // One public member variable

   int SomeNumber;


// Definition of the function

void MyClass::SomeFunction()


   // Output the number

   System::Console::WriteLine(“SomeNumber is: {0}”,


As you can see here, a new class is created with a function and a variable, both public so they can be accessed from outside of the class. Also, below, the definition of the function is included. This function outputs the value which the SomeNumber variable holds.

Let’s move on to the main file of this application, which is OrganizedClass.cpp. This is the file in which we’re going to create a new instance of the class defined in the header. So open the file and inside use the following code:

#include “stdafx.h”

// Including the header file we created

#include “MyHeader.h”


using namespace System;

int _tmain()


// Create a new instance of MyClass named mc

MyClass mc;

// Set the public variable of MyClass

mc.SomeNumber = 13;

// Call the public function of MyClass


return 0;


First thing you can notice is the inclusion of the MyHeader.h file. Now that we included this file we can make use of its content. And that’s what we are doing. You can see the creation of mc which is an instance of MyClass which is defined in the header file. Next a value is assigned to the public variable of the class and the function is called – also a public member of the class with its definition in the header file.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top