Pushkar Dk
Pushkar Dk

Reputation: 13

Classes in header files - not able to compile?

I'm a newbie to c++. I am trying to create header files in c++ to put classes in them and include it in the main fn. Everything works fine when i declare only functions(not class member fns.) in .h file and their definition in a .cpp file of same name. But it gives some error while compiling a project when classes have been defined in the header file! Please help me in solving this problem as I did not find anything useful on the net (google).

Here is my code :

// STUDENT.h
#ifndef STUDENT
#define STUDENT

class STUDENT
{
private :
int marks;
public :
void setMarks(int);
void getMarks();
};

#endif

//STUDENT.cpp

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

void STUDENT :: setMarks(int x)
{
marks = x;
}

void STUDENT :: getMarks()
{
cout << marks;
}

// main.cpp

#include <cstdlib>
#include <iostream>
#include "STUDENT.h"

using namespace std;

int main(int argc, char *argv[])
{
system("PAUSE");
return EXIT_SUCCESS;
}

Additional Details Errors show on dev c++ :

(3)in file included from main.cpp (5)an anonymous union can't have fn. members (11)abstract declarator ' ' used as declaration (11)namespace-scope anonymous aggregates must be static

P.S I still haven't used objects of class in main. just wanted to test it b4 writing actual program

Upvotes: 1

Views: 1789

Answers (3)

cppcoder
cppcoder

Reputation: 23135

Rename the header guards as below and you should be ok

#ifndef STUDENT_H
#define STUDENT_H

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409432

Your problem are these two lines:

#define STUDENT

class STUDENT

The first of those tells the pre-processor to define a macro named STUDENT and with an empty body. When the pre-processor then sees any mention of STUDENT it replaces that with the body, in this case nothing (since the macro body is empty).

To solve this, either change the #define or change the class name.

Upvotes: 1

Konrad Rudolph
Konrad Rudolph

Reputation: 546025

The preprocessor sees this:

#define STUDENT

class STUDENT
{
    …
};

The compiler (after preprocessing) sees this:

class
{
    …
};

Upvotes: 7

Related Questions