simulate
simulate

Reputation: 1263

Using an object outside of its declaration file (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)

Upvotes: 0

Views: 114

Answers (3)

Surt
Surt

Reputation: 16099

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
}

Upvotes: 1

rustyx
rustyx

Reputation: 85361

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.

Upvotes: 0

Apekshit Tewathia
Apekshit Tewathia

Reputation: 33

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);

Upvotes: 0

Related Questions