Reputation: 930
I have a base class in the file base.h
#ifdef _BASE_H_
#define _BASE_H_
class base {
public:
int base_data;
};
#endif
and a derived class
#include "base.h"
class derived: public base {
public:
int derived1_data;
inline void set(int data) { derived1_data = data;}
};
When I try to compile I get this error:
error: expected class-name before ‘{’ token
I am not sure what I am doing wrong here.
Upvotes: 2
Views: 2188
Reputation: 1438
The problem is with the first line of your header file #ifdef _BASE_H_
. It should be #ifndef _BASE_H_
(notice the extra 'n')
Here is a brief explanation of what is happening:
#ifdef MACRO_NAME
<line 1>
<line 2>
...
#endif
This code tells the C++ preprocessor to only include the line1, line2, ... in the source code if a macro MACRO_NAME
has been defined prior to this point (Note: It's just the definition of the macro which matters, not it's value. If you want to predicate code inclusion on macro value, you may use #if
)
The technique you are trying to use here is called Include Guard, and it safeguards against the duplicate inclusion of code (mostly by #include
preprocessor directive). The idea is include source code of a header file only if some macro (say "M") has not been defined yet, and then inside the header file code the first thing you do is define that macro "M" (so that next call to #include samefile
will not include its code again). For creating a Include guard you need to use the #ifndef
preprocessor directive (which is the exact opposite of #ifdef
, in fact, the extra n stands for "NOT").
Since you incorrectly used #ifdef
, the file base.h
was never included (as the only place you define the macro _BASE_H_
is after checking that it is already defined!). Thus the compiler does not know about the class base
, leading to the error expected class-name before ‘{’ token
Upvotes: 2
Reputation: 45665
Despite from the fact that the name of the macro should not start with an underscore, you have a mistake in the "header guard"
#ifdef _BASE_H_
This will only compile the stuff up to #endif
if the macro was already defined, the opposite of what you want to do. That's why you should write
#ifndef _BASE_H_
which essentially ignores the stuff up to #endif
if the macro was already defined, which is the case if the file was already be included.
But your compiler can't detect that this is the real problem. Instead, it silently ignores the contents of the header file base.h
, which means that the base class will never be defined (it will not find the source code!). So when reaching the line
class derived : public base {
the compiler doesn't know the type base
, which means you can't derive from it, hence the error message that a class name was expected.
Upvotes: 1
Reputation: 4571
#ifdef _BASE_H_
should be #ifndef _BASE_H_
.
Or simply use #pragma once
:)
Upvotes: 4
Reputation: 310910
Change in the header
#ifdef _BASE_H_
to
#ifndef _BASE_H_
Upvotes: 2