Mister R2 Mister R2 - 3 months ago 17
C++ Question

Single class has a Class Redefinition Error

I'm new to C++, and I'm having a problem with my class definitions in a header file.
The code for the header file (Student.h) is:

#include <string>
using namespace std;

class Student
{
// Data Members for a Student
string id;
string preferences[3];
int skill;

// Constructor
public:
Student(){}

public:
void SetID(string str)
{ this->id = str; }
public:
void SetSkill(int i)
{ this->skill = i; }
public:
void SetPreferences(int i, string s)
{
this->preferences[i] = s;
}
};

class StudentSchedule
{
public:
StudentSchedule(){}
};


The compiler error says that line 14 (class Student) is a redefinition of 'Student', and that line 15 ({ -- the open brace following class Student) is the previous definition of 'Student'.
The same error on the first two consecutive lines exists for the StudentSchedule class.

I have no .c, .cpp, or .h files anywhere in my compilation that define either class. I have no idea why I'm getting this error.

Answer

You need header guards on that header file. It is presumably being included twice.

Modify the header, adding these lines to the beginning and end.

#ifndef STUDENT_H
#define STUDENT_H

// Put the entire contents of your header here...

#endif

The define doesn't need to be STUDENT_H... it just needs to be unique.

With these directives added, the compiler will ignore all contents of the header file if it has already been parsed.