I saw this code in a textbook and I tried to put in my eclipse IDE, but it didn't work:

#include "GradeBook.h"
#include <iostream>
using namespace std;

// GradeBook class definition
class GradeBook
{
public:
   // function that displays a welcome message to the GradeBook user
   void displayMessage()
   {
      cout << "Welcome to the Grade Book!" << endl;
   } // end function displayMessage
}; // end class GradeBook  

// function main begins program execution
int main()
{
   GradeBook myGradeBook; // create a GradeBook object named myGradeBook
   myGradeBook.displayMessage(); // call object's displayMessage function	
} // end main

However, when I got rid of the header file declaration

#include "GradeBook.h"

the codes compiled properly.

The header file's content is:

#ifndef GRADEBOOK_H_
#define GRADEBOOK_H_

class GradeBook {
};

#endif

Why does this happen? And why do IDE's create header files? This confuses me, because I'm used to seeing a class declaration and putting codes within it. By including the header file I just write a whole bunch of codes. Do you guys all program with header files too?

The problem with the code above is the class GradeBook is getting declared twice. Once in the header file and once in your code. So when you remove the header file "GradeBook.h", the code compiles properly.

And about your query of programing with header files. Dividing programs into files makes your code more manageable and it supports re-usability of code. It doesn't make much difference in small programs like this one but its really useful in big programs.

The problem with the code above is the class GradeBook is getting declared twice. Once in the header file and once in your code. So when you remove the header file "GradeBook.h", the code compiles properly.

And about your query of programing with header files. Dividing programs into files makes your code more manageable and it supports re-usability of code. It doesn't make much difference in small programs like this one but its really useful in big programs.

Ok. Automatically, the IDE I use creates a header file whenever I create a class file. Are there points in time when developers have to alter or tweak the header files?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.