i’m learning c++. i know quite well java and python, but i’m getting mad in using a little design pattern fancy in my c++ trials.
here are my files, i think that they are quite auto-explicative, if there are some question, comment are welcome!
i have a class Engine that has a Behaviour.. i want to sublass Behaviour into different specific behaviours.. but it’s quite easy also without subclass..
main.cpp :
#include "Engine.h"
int main() {
Engine e;
e.work();
return 0;
};
Engine.h :
#ifndef ENGINE_H_
#define ENGINE_H_
#include <iostream>
#include "Behaviour.h"
class Engine {
public:
Engine() {
std::cout << "Engine constructor" << std::endl;
this->b = new Behaviour(this);
};
virtual ~Engine(){};
void work() {
std::cout << "Engine work" << std::endl;
};
int getFoo() { return 42; };
private:
Behaviour * b;
};
#endif /* ENGINE_H_ */
Behaviour.h :
#ifndef BEHAVIOUR_H_
#define BEHAVIOUR_H_
#include <iostream>
#include "Engine.h"
class Behaviour {
public:
Behaviour(Engine* e) {
std::cout << "behaviour constructor, kind of abstract class" << std::endl;
this->e = e;
};
virtual ~Behaviour(){};
void work() {
std::cout << "Behaviour work" << this->e->getFoo() << std::endl;
};
protected:
Engine * e;
};
#endif /* BEHAVIOUR_H_ */
my compiler errors:
$ rm *.gch; c++ *
In file included from Behaviour.h:5:
Engine.h:26: error: ISO C++ forbids declaration of ‘Behaviour’ with no type
Engine.h:26: error: expected ‘;’ before ‘*’ token
Engine.h: In constructor ‘Engine::Engine()’:
Engine.h:14: error: ‘class Engine’ has no member named ‘b’
Engine.h:14: error: expected type-specifier before ‘Behaviour’
Engine.h:14: error: expected ‘;’ before ‘Behaviour’
In file included from Engine.h:5:
Behaviour.h:11: error: expected ‘)’ before ‘*’ token
Behaviour.h:23: error: ISO C++ forbids declaration of ‘Engine’ with no type
Behaviour.h:23: error: expected ‘;’ before ‘*’ token
Behaviour.h: In member function ‘void Behaviour::work()’:
Behaviour.h:19: error: ‘class Behaviour’ has no member named ‘e’
Engine.h: In constructor ‘Engine::Engine()’:
Engine.h:14: error: no matching function for call to ‘Behaviour::Behaviour(Engine* const)’
Behaviour.h:7: note: candidates are: Behaviour::Behaviour()
Behaviour.h:7: note: Behaviour::Behaviour(const Behaviour&)
i think i need some forward declarations but i’m not sure and looking through tutorials and make some trials does not resolve my problems at all.
In
Engine.hreplace the include with a forward declaration:with
Same for
class Engine;insideBehavior.h.Because you have a cyclic dependency, you’ll need to use forward declarations instead of includes.
You’ll also need to separate the implementation in a
cppfile. A forward declaration alone won’t let you callthis->b = new Behaviour(this);.Also, take some time to rethink your design. This sort of dependancy is usually a code smell.