Base class undefined - c++

I know it is one of the constant ask question
so i get this error
'WorldObject': [Base class undefined (translated from german)]
Here is the code which produce this error:
ProjectilObject.h:
#pragma once
#ifndef _PROJECTILOBJECT_H_
#define _PROJECTILOBJECT_H_
#include "GameObjects.h"
class ProjectilObject: public WorldObject
{
public:
ProjectilObject(IGameObject* parent,int projectiltype);
void deleteyourself();
protected:
virtual void VProcEvent( long hashvalue, std::stringstream &stream);
virtual void VInit();
virtual void VInitfromStream( std::stringstream &stream );
virtual void VonUpdate();
virtual void VonRender();
private:
vec3 vel;
float lifetime;
float lifetimeend;
vec3 target;
int m_projectiltype;
};
#endif
Here is the code file from the WorldObject class:
GameObjects.h:
#pragma once
#ifndef _GAMEONJECTCODE_H_
#define _GAMEONJECTCODE_H_
#include "IGameObject.h"
#include "Sprite.h"
#include "GamePath.h"
#include "HashedString/String.h"
#include "IAttribute.h"
#include "CharacterObjects.h"
#include "ProjectilObject.h"
[...]
class WorldObject: public IGameObject, public MRenderAble
{
public:
WorldObject(IGameObject* parent);
virtual bool IsDestroyAble();
virtual bool IsMageAble();
virtual bool IsRenderAble();
protected:
virtual void VProcEvent( long hashvalue, std::stringstream &stream);
virtual void VonUpdate();
virtual void VonRender();
virtual void VInit() =0;
virtual void VInitfromStream( std::stringstream &stream ) =0;
virtual void VSerialize( std::stringstream &stream );
vec3 poscam;
};
[...]
#endif
There are some other Classes in this file but they shouldn't interrupt, I think.
Maybe there is a tiny error I didn't saw but I don't understand why this error is produced. When you need more of the code feel free to ask because i think it would only disturb.

If you have any source file that includes GameObjects.h before ProjectilObject.h or does not include ProjectilObject.h directly, then the compiler will first find the declaration of ProjectilObject through the include in GameObjects.h before knowing what WorldObject is. That is because GameObjects.h first includes ProjectilObject.h and then declares WorldObject. In that case the include of GameObjects.h present in ProjectilObject.h won't work because _GAMEONJECTCODE_H_ will be already defined.
To avoid this, either be sure to include ProjectilObject.h instead of GameObjects.h in your source file, or use forward declarations.

It's hard to answer this question without looking at the whole code. Even a misplaced brace could count. Check your namespaces - are you sure the WorldObject is in the same namespace?
I suggest you use the #pragma message by placing it near the WorldObject definition and checking the compiler output:
#pragma message ("World object is defined")
If it does not show up, move the pragma to the parent .h file and check the compiler output again. With this you can easily locate the error.

class WorldObject;
class ProjectilObject: public WorldObject
You are forward declaring WorldObject, but to inherit from a class you need the definition, so you have to include the header of WorldObject.

In my case: i delete derived class include from base class header file.
for example:
file 1 :
#include "B.h"
-> A()
file 2:
-> B() : A()
solution : delete #include "B.h" from file1

Related

Troubles with Circular Dependencies between 3 classes and with inheritance

I'm a first-year college student that doesn't know everything about CS yet, so please bear with my newness to it, and this is my first question on here.
For an assignment, we are making faux version of Pokemon Go to practice using polymorphism in c++, and I'm running into some compiler errors. Here are the three files with just a sample of the code in them:
#ifndef EVENT_H
#define EVENT_H
#include <string>
#include "Trainer.h"
class Event{
protected:
std::string title;
public:
Event();
~Event();
virtual void action(Trainer) = 0;
};
#endif
Trainer.h:
#ifndef TRAINER_H
#define TRAINER_H
#include "Pokemon.h"
class Trainer{
private:
Pokemon* pokemon;
int num_pokemon;
public:
Trainer();
~Trainer();
//include accessors and mutators for private variables
};
#endif
Pokemon.h:
#ifndef POKEMON_H
#define POKEMON_H
#include "Event.h"
#include <string>
class Pokemon : public Event{
protected:
std::string type;
std::string name;
public:
Pokemon();
~Pokemon();
virtual bool catch_pokemon() = 0;
};
#endif
The trainer.h file is a parent class for each pokemon type (eg Rock) which just defines a few virtual functions. The error I'm getting is when I'm compiling all of this and I get something that says:
Pokemon.h : 5:30: error: expected class-name befoer '{' token:
class Pokemon : Event {
Pokemon need to be a derived class to an event, so that an event pointer can point in another Location class can point to either a pokemon, pokestop, or cave for the assignment, and I have been looking online for hours and can't figure out what to do. I would appreciate the help! Let me know if you need more info or something because again, this is my first time posting a question.
You need some forward declarations.
In Event.h, you can put class Trainer; instead of #include "Trainer.h". In Trainer.h, you can put class Pokemon; instead of #include "Pokemon.h".
You will probably need to include the appropriate headers in the corresponding source files in order to actually use the other classes. But by avoiding the includes in the header files, you get out of the circular dependency trouble.
Pokemon.h must continue to #include "Event.h", since you're inheriting Event, which requires a complete definition.
Use forward declaration, to tell classes the type they need to use will be defined later. You can use forward declaration in situations where the size is know, pointers and references are always the same size regardless of the type they point to so use them.
#ifndef EVENT_H
#define EVENT_H
#include <string>
class Trainer;
class Event
{
protected:
std::string title;
public:
Event();
virtual ~Event();
virtual void action(Trainer* const trainer) = 0;
};
#endif
then
#ifndef TRAINER_H
#define TRAINER_H
class Pokemon;
class Trainer
{
private:
Pokemon* const pokemon;
int numPokemon;
public:
Trainer();
~Trainer();
};
#endif
then
#ifndef POKEMON_H
#define POKEMON_H
#include "Event.h"
#include <string>
class Pokemon : public Event
{
protected:
std::string type;
std::string name;
public:
Pokemon();
virtual ~Pokemon();
virtual bool catchPokemon() = 0;
};
#endif
when using polymorphism (virtual functions) you must always make the base class destructor virtual too. It is also nice to make the derived classes destructor virtual as well, but it is not required.

Abstract classes and class organization in C++

I would like to create a basic abstract class in C++, where the subclasses are each in a separate file. My abstract class looks something like
class Process_Base{
public:
virtual void process() = 0;
}
Should a simple implementation like this be contained entirely in a header file? If it is do I need to have a .cpp file associated with it?
When I create the subclasses what should their header file look? I was thinking .cpp file for the subclass should look something like
#include "Process_Base.h"
class Hello_Process : public Process_Base{
void process(){
printf("%s\n", "Hello, World");
}
}
Could someone verify that I am approaching this correctly, and if not give a simple example of what I should be doing.
UPDATE
I continued with the implementation but I am now getting the following compiler error
g++ -c -Wall -g Process_Message.cpp
Process_Message.cpp:4: error: expected class-name before ‘{’ token
The following is the abstract class header
// Abstract header .hpp file
class Process_Base{
public:
virtual void process() = 0;
};
the subclass header
// The subclass header .hpp file
#include "Process_Base.hpp"
class Process_Message : public Process_Base {
public:
void process();
};
and the implementation
// Simple implementation .cpp file
#include <stdio.h>
#include <string.h>
class Process_Message : Process_Base {
public:
void process(){
printf("%s", "Hello");
}
}
I don't understand why I am getting the error, can someone please explain.
You're missing ; at the end of Process_Base declaration, when you include the file, the compiler goes nut. correct is:
class Process_Base{
public:
virtual void process() = 0;
};
Why this 'Process_Base' is there in below code? You have already mentioned inheritance in header file,right?
// Simple implementation .cpp file
#include <stdio.h>
#include <string.h>
class Process_Message : Process_Base {
public:
void process(){
printf("%s", "Hello");
}
}
Also don't forget to type ';' at the end of the class declaration after '}'
Your correct code should look like this:
//Process_Message.h
#include "Process_Base.hpp"
class Process_Message : public Process_Base {
public:
void process();
};
//Process_Message.cpp
#include <stdio.h>
#include <string.h>
#include "Process_Message.h"
void Process_Message::process()
{
printf("%s", "Hello");
}
Don't forget to declare your overrides as virtual, or they will hide parent methods instead of implementing them.
#include <iostream>
class Process_Base
{
public:
virtual ~Process_Base() {}
virtual void process() =0;
};
class Process_Message : public Process_Base
{
public:
virtual void process(); // <- virtual
};
void Process_Message::process()
{
std::cout << "Hello";
}
The above should compile fine

C++ Method declaration using another class

I'm starting to learn C++ (coming from Java), so bear with me.
I can't seem to get my method declaration to accept a class I've made.
'Context' has not been declared
I think I'm not understanding a fundamental concept, but I don't know what.
Expression.h
#include "Context.h"
class Expression {
public:
void interpret(Context *); // This line has the error
Expression();
virtual ~Expression();
};
Context.h
#include <stack>
#include <vector>
#include "Expression.h"
class Context {
private:
std::stack<Expression*,std::vector<Expression*> > theStack;
public:
Context();
virtual ~Context();
};
You have to forward declare Expression in Context or vice versa (or both), otherwise you have a cyclic dependency. For example,
Expression.h:
class Context; // no include, we only have Context*.
class Expression {
public:
void interpret(Context *); // This line has the error
Expression();
virtual ~Expression();
};
Context.h:
#include <stack>
#include <vector>
class Expression; // No include, we only have Expression*
class Context {
private:
std::stack<Expression*,std::vector<Expression*> > theStack;
public:
Context();
virtual ~Context();
};
You can perform the forward declarations because the full definition of the classes isn't needed, since you are only referring to pointers to the other class in each case. It is likely that you will need the includes in the implementation files (that is, #include "Context.h" in Expression.cpp and #include Expression.h in Context.cpp).
Finally, remember to put include guards in your header files.
In C++, class definitions always have to end with a semi-colon ;
so example:
class foo {};
Java and C# doesn't require that, so I can see your confusion.
Also it looks like both your header files include each other. Thus it's kind of like a snake eating it's tail: Where does it start? Thus in your Expression.h you can replace the 'include' with a forward declaration instead:
class Context;
class Expression {
public:
void interpret(Context *); // This line has the error
Expression();
virtual ~Expression();
}
And last but not least, you should put a compiler guard to prevent the header from getting included more than once into a .cpp file. You can put a #pragma once in the top of the header file. That is useful if you are using visual studio and the microsoft compiler. I don't know if GCC supports it or not. Or you can wrap your header file like this:
#ifndef EXPRESSION_H_
#define EXPRESSION_H_
class Context;
class Expression {
public:
void interpret(Context *); // This line has the error
Expression();
virtual ~Expression();
}
#endif
you might need to forward declare the classes Context and Expression in the header files before the #include
e.g.
#include <stack>
#include <vector>
// forward declaration
class Context;
class Expression;
#include "Expression.h"
class Context {
private:
std::stack<Expression*,std::vector<Expression*> > theStack;
public:
Context();
virtual ~Context();
}

Accessing Static Method and Static bool in other class

I have a base interface class:
class A
{
public:
ITask(){}
virtual bool Start()=0;
virtual void Update()=0;
virtual void Stop()=0;
};
I now have 2 other classes, that inherit from this
#include "A.h"
#include "C.h"
class B: public A
{
public:
bool Start(){}
void Update()
{
c.Start();
}
void Stop(){}
static bool m_run;
static void SetRun(bool run)
{
m_run = run;
}
private:
C c;
};
lastly I have a 3rd class:
#include "A.h"
#include "B.h"
class C : public A
{
public:
bool Start()
{
B::SetRun(false); // cant do this
B::m_run = false; // or this
}
void Update()
{
}
void Stop()
{
}
}
I have shaved down some of the code, for simplicity.
I dont understand why I cant access the static var in B. Do I need to make it a pointer or a ref?
I get 2 errors:
error C2653: 'B' : is not a class or namespace name
error C3861: 'm_run': identifier not found
Although you don't show it, I'm assuming that B.h includes C.h; otherwise the line C c; won't compile. This causes a circular dependency in the header files: B.h must be included before C.h, which must be included before B.h, which is impossible.
The easiest solution is to move the body of C::Start out of the definition of C, so that C.h does not need to include B.h. The function definition can go into a source file, or a separate header if you want to keep it inline.
Alternatively, you could modify B to contain a std::unique_ptr<C> rather than an instance of C, and implement a constructor (in a source file, or a separate header) that initialises it with new C. Then B.h only needs to forward declare class C; rather than including C.h.
A better solution, if possible, would be to rethink the relationships between the classes so that there isn't a circular dependency.
(UPDATE: while I was writing this answer, the question changed to show that B.h does indeed include C.h as I guessed.)
There is nothing wrong with your example code (after the edits), the problem must be somewhere else, like a failed include.

multiple declaration error- virtual functions

I have observer.h , client.h and field.h files.
In observer.h there is Subject class which has
// observer.h
class Subject {
public:
virtual ~Subject(){};
Subject(){};
virtual void Attach(Observer*);
virtual void Detach(Observer*);
virtual void Notify(bool _value);
virtual bool getCheckedIn(){};
private:
vector < Observer* > _observers;
};
#ifndef CLIENT_H
#define CLIENT_H
#include "Field.h"
class Client : public Subject {
public:
Client(string _name, Field *_field) : client_name(_name) ,field(_field) , checked_in(false) {}
void setCheckedIn(bool _value){
checked_in = _value;
Notify(_value);
}
void enterRow(string _row_name){
field->deneme();
setCheckedIn(true);
}
bool getCheckedIn(){ return checked_in;}
private:
bool checked_in;
string client_name;
Field *field;
};
#endif // CLIENT_H
#ifndef Field_H
#define Field_H
#include "CreateRow_absFac.h"
#include "observer_pattern.h"
#include <vector>
#include <string>
using namespace std;
// Template Class
class Field{
public:
Field();
// Template method
void field_creator();
virtual void setAbstractRow() = 0;
protected:
FarmFactory *abstract_row1;
FarmFactory *abstract_row2;
FarmFactory *abstract_row3;
Rows *row1 ;
Rows *row2 ;
Rows *row3 ;
Sensor sensor1;
};
When compiled , got this error :
ld: duplicate symbol Subject::Notify(bool) in /Users/barisatamer/Desktop/se311/PROJECT/build/PROJECT.build/Debug/PROJECT.build/Objects-normal/x86_64/Field.o and /Users/barisatamer/Desktop/se311/PROJECT/build/PROJECT.build/Debug/PROJECT.build/Objects-normal/x86_64/main.o
If I remove virtual functions it compiles without error. What is the problem with virtual functions ?
We can't actually see it here, but the problem is probably that you defined Subject::notify(bool) in a header file (your observer.h just declares it, it doesn't define it) and you included that header file in both Field.cpp and main.cpp, so you get multiple definitions. The fix is to move the definition into a source file so its only defined once.
General rule -- DECLARE things in header files, DEFINE them in non-header source files. Note that include guards are irrelevant here -- they prevent something being declared multiple times in a single compilation unit, but what's needed is to avoid defining something multiple times in different compilation units.
Try keeping header guards even for your observer.h. BTW, Why aren't you overriding virtual functions in the derived class ?
Apparently you have an ODR violation. Why did you get away with non-virtual functions? Possibly because you defined them inline (e.g. in class). As it was suggested, check the include guards and function definitions.