c++structincludeheaderheader-files

C++, how to declare a struct in a header file


I've been trying to include a structure called "student" in a student.h file, but I'm not quite sure how to do it.

My student.h file code consists of entirely:

#include<string>
using namespace std;

struct Student;

while the student.cpp file consists of entirely:

#include<string>
using namespace std;

struct Student {
    string lastName, firstName;
    //long list of other strings... just strings though
};

Unfortunately, files that use #include "student.h" come up with numerous errors like

error C2027: use of undefined type 'Student'

error C2079: 'newStudent' uses undefined struct 'Student'  (where newStudent is a function with a `Student` parameter)

error C2228: left of '.lastName' must have class/struct/union 

It appears the compiler (VC++) does not recognize struct Student from "student.h"?

How can I declare struct Student in "student.h" so that I can just #include "student.h" and start using the struct?


Solution

  • You should not place an using directive in an header file, it creates unnecessary headaches.

    Also you need an include guard in your header.

    EDIT: of course, after having fixed the include guard issue, you also need a complete declaration of student in the header file. As pointed out by others the forward declaration is not sufficient in your case.