Using an object outside of its declaration file (C++) - c++

(it is be possible that this question has been asked very often already and i am sorry about this repost, but anything i found just didnt help me, since i am relatively a beginner at c++)
so here is an example to show my problem
i have the class monster
class Monster{
public:
Monster();
void attack();
private:
int _health;
int _damage;
};
and i have the class Level
class Level{
Level();
};
i have created the object "snake" from the class Monster in my "main.cpp"
#include "Monster.h"
int main(){
Monster snake;
}
now what do i do if i want to use "snake" in my "Level" class? if i want to do "snake.attack();" inside of "Level.cpp" for example?
If i declare it again in "Level.cpp" it will be a seperate object with its own attributes wont it?
i have always been making the member functions of my classes static until now, so i could do "Monster::attack();" anywhere in my program but with this tachnique i cant have multiple objects doing different things depending on their attributes (snake1, snake2, bat1, etc...)
thanks for the help in advance!
(and sorry for the possibly reoccuring question)

Presuming those snips are your .h files.
Your level.cpp should something like this:
#include "level.h" // its own header
#include "monster.h" // header with Monster::attack() declaration
Level::DoAttack(Monster& monster) { // using snake as parameter.
health = health - monster.attack(); // monster hits us, subtract health.
}
monster.h would be
class Monster{
public:
Monster();
void attack();
private:
int _health;
int _damage;
};
and monster.cpp
Monster::attack() {
// code to calculate the attack
}

I could not completely understand your questions.But from what I understood.I think you want to access a Monster object instantiated in main() to be used inside level.So,here is what you can do.Add a constructor inside the level class which takes a monster object as an argument.Then instantiate a level object and pass the monster object in it.Like this,
Level l=new Level(snake);

By declaring a class you're not creating any objects. You normally declare a class by including the corresponding header file.
So, in Level.h you'd #include <Monster.h>, then you can reference it inside Level.
But seriously, you can't write much C++ code without understanding the basic things such as declaration vs. definition, header files (.h), classes vs. objects, pointers and references, etc. It would be best to invest in a book or at least to read some tutorials online.

Related

Nested classes definition and initiation through files

I'm trying to make class functions I can tack on to other classes, like with nested classes. I'm still fairly new to C++, so I may not actually be trying to use nested classes, but to the best of my knowledge that's where I'm at.
Now, I've just written this in Chrome, so it has no real use, but I wanted to keep the code short.
I'm compiling on Windows 7, using Visual Studio 2015.
I have two classes in file_1.h:
#pragma once
#include "file_2.h"
class magic_beans{
public:
magic_beans();
~magic_beans();
int getTotal();
private:
double total[2]; //they have magic fractions
}
class magic_box{
public:
magic_box(); //initiate
~magic_box(); //make sure all objects have been executed
void update();
magic_beans beans; //works fine
magic_apples apples; //does not work
private:
int true_rand; //because it's magic
};
... And I have one class in file_2.h:
#pragma once
#include "file_1.h"
class magic_apples{
public:
magic_apples();
~magic_apples();
int getTotal();
private:
double total[2];
}
Now, I've found that I can simply change:
magic_apples apples;
To:
class magic_apples *apples;
And in my constructor I add:
apples = new magic_apples;
And in my destructor, before you ask:
delete apples;
Why must I refer to a class defined in an external file using pointers, whereas one locally defined is fine?
Ideally I would like to be able to define magic_apples the same way I can define magic_beans. I'm not against using pointers but to keep my code fairly uniform I'm interested in finding an alternative definition method.
I have tried a few alternative defines of magic_apples within my magic_box class in file_1.h but I have been unable to get anything else to work.
You have a circular dependency, file_1.h depends on file_2.h which depends on file_1.h etc. No amount of header include guards or pragmas can solve that problem.
There are two ways of solving the problem, and one way is by using forward declarations and pointers. Pointers solve it because using a pointer you don't need a complete type.
The other way to solve it is to break the circular dependency. By looking at your structures that you show, it seems magic_apples doesn't need the magic_beans type, so you can break the circle by simply not includeing file_1.h. So file_2.h should look like
#pragma once
// Note no include file here!
class magic_apples{
public:
magic_apples();
~magic_apples();
int getTotal();
private:
double total[2];
}

c++ class circular reference?

I am working on a little game engine but I got stuck at something. Explanation : I have two classes, cEntity And ObjectFactory :
cEntity
class cEntity:public cEntityProperty
{
Vector2 position;
Vector2 scale;
public:
cEntity(void);
cEntity(const cEntity&);
~cEntity(void);
public:
void init();
void render();
void update();
void release();
};
ObjectFactory
#include "cEntity.h"
#include <vector>
class ObjectFactory
{
static std::vector<cEntity> *entityList;
static int i, j;
public:
static void addEntity(cEntity entity) {
entityList->push_back(entity);
}
private:
ObjectFactory(void);
~ObjectFactory(void);
};
std::vector<cEntity> *ObjectFactory::entityList = new std::vector<cEntity>();
Now I am adding new cEnity to ObjectFactory in cEntity constructor but facing an error related to circular references: for using ObjectFactor::addEntity() I need to define the ObjectFactory.h in cEntity class but it creates a circular reference.
I think your code might have an underlying architectural issue given how you have described the problem.
Your ObjectFactory should be handling the cEntities, which in turn should be unaware of the "level above". From the description of the problem you are having, it implies that you're not sure what class is in charge of what job.
Your cEntitys should expose an interface (i.e. all the stuff marked "public" in a class) that other bits of code interact with. Your ObjectFactory (which is a bit badly named if doing this job, but whatever) should in turn use that interface. The cEntitys shouldn't care who is using the interface: they have one job to do, and they do it. The ObjectFactory should have one job to do that requires it to keep a list of cEntitys around. You don't edit std::string when you use it elsewhere: why is your class any different?
That being said, there's two parts to resolving circular dependencies (beyond "Don't create code that has circular dependencies in the first place" - see the first part to this answer. That's the best way to avoid this sort of problem in my opinion)
1) Include guards. Do something like this to each header (.h) file:
#ifndef CENTITY_H
#define CENTITY_H
class cEntity:public cEntityProperty
{
Vector2 position;
Vector2 scale;
public:
cEntity(void);
cEntity(const cEntity&);
~cEntity(void);
public:
void init();
void render();
void update();
void release();
};
#endif
What this does:
The first time your file is included, CENTITY_H is not defined. The ifndef macro is thus true, and moves to the next line (defining CENTITY_H), before it moves onto the rest of your header.
The second time (and all future times), CENTITY_H is defined, so the ifndef macro skips straight to the endif, skipping your header. Subsequently, your header code only ever ends up in your compiled program once. If you want more details, try looking up how the Linker process.
2) Forward-declaration of your classes.
If ClassA needs a member of type ClassB, and ClassB needs a member of type ClassA you have a problem: neither class knows how much memory it needs to be allocated because it's dependant on another class containing itself.
The solution is that you have a pointer to the other class. Pointers are a fixed and known size by the compiler, so we don't have a problem. We do, however, need to tell the compiler to not worry too much if it runs into a symbol (class name) that we haven't previously defined yet, so we just add class Whatever; before we start using it.
In your case, change cEntity instances to pointers, and forward-declare the class at the start. You are now able to freely use ObjectFactory in cEntity.
#include "cEntity.h"
#include <vector>
class cEntity; // Compiler knows that we'll totally define this later, if we haven't already
class ObjectFactory
{
static std::vector<cEntity*> *entityList; // vector of pointers
static int i, j;
public:
static void addEntity(cEntity* entity) {
entityList->push_back(entity);
}
// Equally valid would be:
// static void addEntity(cEntity entity) {
// entityList->push_back(&entity);}
// (in both cases, you're pushing an address onto the vector.)
// Function arguments don't matter when the class is trying to work out how big it is in memory
private:
ObjectFactory(void);
~ObjectFactory(void);
};
std::vector<cEntity*> *ObjectFactory::entityList = new std::vector<cEntity*>();

How can two Classes in C++ notice each other? [duplicate]

This question already has answers here:
Resolve build errors due to circular dependency amongst classes
(12 answers)
Cross referencing included headers in c++ program
(5 answers)
Closed 9 years ago.
For example a little Computergame with three Classes Player, Bot and Game
Player has a Method that checks if the Player collide with a bot
// Player.h
#include Game.h
#include Bot.h
class Player {
private:
bool collision(Game g) {
for (Bot bot: g.bots)
...
}
};
The Bot.h (kept simple, of cause it has some other attributes like actual position and so far)
// Bot.h
class Bot {
public:
Bot()
};
The Gameclass handles the Gameloop and the List of Bots
//Game.h
#include Bot.h
#include Player.h
class Game {
public:
Player player:
std::vector<Bot> bots
void loop() { player.collision() }
};
So here we have the problem that Game.h includes Player.h and the other way around.
How can I resolve this?
While the other answers here are certainly technically correct, whenever I come across a situation like this I see it as pointing out a potential flaw in my design. What you have is cyclic dependencies, like so:
This isn't just a problem for your implementation, it means that there is too much coupling between classes, or, conversely, too little information hiding. This means that you can't design the Player independently of the Game, for example.
So if possible, I'd prefer a situation like this, where the Game, as the controller delegates work out to other classes.
One way to do this is for the Game to pass references to its own properties as and when the Player needs them.
For example have collision take a bots parameter rather than the `Game
bool collision(const std::vector<Bot&> bots) {
// note pass objects by const ref is usu preferred in C++ to pass by value
for (Bot bot: g.bots)
...
}
(Note in a more sophisticated approach, it could pass interfaces, i.e. abstract base classes, onto itself).
If all else fails, you can go back to using a forward declaration.
In this case the easiest thing would be a forward declaration, and moving some code from the header file to the source file.
Like this
Player.h
#include "Bot.h"
class Game; // forward declaration
class Player {
private:
bool collision(Game g);
};
Player.cpp
#include "Player.h"
#include "Game.h"
bool Player::collision(Game g) {
for (Bot bot: g.bots)
...
}
The forward declaration tells the compiler that Game is the name of a class but nothing else. So the Player::collision method must be moved to the Player.cpp file where the full definition of Game is available.
I dont think you can do this since If A contains B, and B contains A, it would be infinite size. Infact you can create two classes that store pointers to one another, by using the forward declaration, so that the two classes know of each other's existence
Forward declaration is required - http://en.wikipedia.org/wiki/Forward_declaration

Children Accessing Elements of Other Children of the Same Parent

I'm currently developing an RPG game using C++ and I got to the point of including events on the map.
I wanted to be able to have the event on the map heal the player. I figured the easiest way to do this was to pass a pointer to the event object from the game using the 'this' keyword. When I got into doing this there were a whole bunch of compiler errors that seem to have resulted from trying to include a class that was currently attempting to include the other class. (endless loop I guess?)
For example. I have my 'game' class and it has a public member belonging to the 'mapManager' class. The 'mapManager' object then has the 'event' object as a member. The 'game' object also has a 'player' object within its' members. I need to have the 'event' object change variables that the 'player' has. I could honestly throw pointers whenever I need them but this might get cumbersome.
What I'm trying to ask is if there is an easy way to have a child of a parent access another child of that parent or if it would just be easier to throw pointers to all of the child classes needing them pointing to the other children.
Wow... that made very little sense but hopefully someone can understand enough to give me a good answer. Here's some code in case it helps.
:game.h
include "player.h"
include "event.h"
class game
{
public:
player Player;
event Event;
};
:player.h
class player
{
public:
game* Game;
};
:event.h
class event
{
public:
game* Game;
};
Having just this results in "game does not name a type" and so I tried to include game in event.h and player.h and got the same error. What I want to do is be able to access player's variable HP from inside event.
It's preferable to avoid circular references where possible; however if you really want to do that, then the solution is to forward-declare your class Game at the top of the header files which will be using references/pointers to it. e.g.
#ifndef EVENTH
#define EVENTH
class Game;
class Event
{
Game* game;
};
#endif
and..
#ifndef PLAYERH
#define PLAYERH
class Game;
class Player
{
Game* game;
};
#endif
For header files which need no knowlege of the implementation/sizeof the Game class, a simple forward-declaration is sufficient to let the compiler know that a class with that name exists.
In your .cpp source files (where the implementation of Game is actually important and used by Player/Event implementation) you will still need to #include the header containing your Game class definition.
//game.h
class event;
class game {
event _e;
private:
game(){}
//game& operator=(game& other) {}
~game(){}
public:
static game & getInstance() {
static game instance;
return instance;
}
event& getEvent() {return _e;}
};
//HealEventObserver.h
class HealEventObserver {
public:
virtual void heal() = 0;
virtual ~HealEventObserver(){}
};
//player.h include game.h and HealEventObserver.h event.h
class Player : public HealEventObserver
{
public:
virtual void heal() {/*heal the player*/}
Player() {
game& instance = game::getInstance();
event& e = instance.getEvent();
e.registerObserver(this);
}
};
//event.h include HealEventObserver.h
class event {
std::set<HealEventObserver*> _observers;
void notify() {
std::set<HealEventObserver*>::iterator it = _observers.begin();
std::set<HealEventObserver*>::iterator end = _observers.end();
for( ;it!=end; ++it) {
it->heal();
}
}
public:
void registerObserver(HealEventObserver* observer) {_observers.insert(observer);}
};
Don't make your event object change the player at all just make the event tell the player to heal himself. Also if game is suppose to represent everything then make it global.
To Answer the comment: (This is just my opinion and nothing else.)
After a bit of research i found this link that gives the names of great references.
The Definitive C++ Book Guide and List

Classes, namespaces and inheritance help for D&D game

So for class we have to make a D&D 3.5 game, and for the first assignment I have to generate a Fighter character. The way I have the hierarchy set up in my head is character.cpp and it's child is classname.cpp where it has some attributes specific to the class since all classes share the same basic things.
Is that a good structure for it? If it's related we haven't done STL yet.
Another issue that arose is since my teammate will be making a GUI for the game he may also make a class called character. I thought to resolve this I would make a namespace. But if I make each of the files I make have their class inside namespace d20 in each of their respective headers would all of those namespaces be one and the same? I can't think of a very good way to word this question.
Here's my best stab at answering you...
A good inheritance structure is very context specific, but the basic principle is a base class contains data and functions relevant to all the derived classes. Derived classes will contain specific data and functions to itself. In your case there will be a lot of data in the base class 'character' like all the character stats and functions that compute outcome based on stats (I'm assuming the rules of the game are generally class independent).
I'm also assuming when you say 'classname.cpp' you mean 'fighter.cpp', 'cleric.cpp', etc. In that case, yes, I would agree with making it structured that way.
STL doesn't really have a direct impact on coming up with class hierarchies, so I would say no, it's not related.
As for namespaces, anytime you specify a namespace it will be the same as anywhere else you specify the exact same name (which is what I think you're asking). You don't need to do anything special to make it the same namespace other than naming it the same exact thing. A simple example is as follows:
character.h
namespace d20
{
class Character
{
Character();
~Character();
//etc...
}
}
character.cpp
#include "character.h"
namespace d20
{
Character::Character()
{
// Stuff...
}
Character::~Character()
{
}
}
fighter.h
#include "character.h"
namespace d20
{
class Fighter : public Character
{
Fighter ();
~Fighter ();
//etc...
}
}
OR (without the namespace keyword)
#include "character.h"
class Fighter : public d20::Character
{
Fighter ();
~Fighter ();
//etc...
}
Edit: Please note that in the second case the Fighter class is NOT is the namespace d20, it just derives from a class in that namespace.
For your case I would recommend against inheritance, because inheritance is usually used two ways: where you always use the base class, and never upcast, or using inheritance. The first is not what you want, and the second can be slightly tricky. (Also makes multiclassing impossible) In the long run, a very generic character class will get you farther.
namespace d20 {
enum classtype {warrior_class, cleric_class, rogue_class, mage_class};
class character {
classtype charclass;
int hp;
int bab;
int str;
string get_name();
void hit(character* enemy);
};
}
On the other hand, if this is simply a homework assignment, and you want to keep things super simple, inheritance with virtual functions might make simple programs easier.
namespace d20 {
class character {
int hp;
int bab;
int str;
virtual string get_name() = 0;
virtual void hit(character* enemy) const;
};
}
namespace d20 {
class fighter {
string get_name() {return "Fighter";}
void hit(character* enemy);
}
}
That sounds like a reasonable approach to me. Presumably classname.cpps would be better named as something like cleric.cpp, barbarian.cpp etc.
You could make your baseclass with a protected function like 'rollstats' to return a string containing stats. Child classes could then override that with a public rollstats function which calls the the base class' method and then append additional stats.
If your classmate is creating the GUI, he should be using your classes shouldn't he? In which case he should just be importing your .h / .cpp files and there's no need to necessarily worry about namespaces.