Posted: Wed Apr 07, 2010 7:13 pm Post subject: Calling a function from another class
Hi.
I'm making a little text based battle game and I need to know how to call a function from another class.
I'll give you an example of what I want to do.
(it's not in full detail)
header file
class Player {
void attack ();
...
.cpp file
void attack () {
cout << "You have inflicted " << damage << " on the enemy \n" ;
(this is where I want to call the function)
Ex: enemy::gethurt ();
how do I make it so that it's possible to call functions from another class?
Sponsor Sponsor
TerranceN
Posted: Wed Apr 07, 2010 7:48 pm Post subject: Re: Calling a function from another class
You should probably post both classes' header files so we at least know how you are using these classes
Assuming the enemy is an instance of an Enemy class, you would need to be able to access that instance in order to call its methods. You can do that by passing a refrence or pointer of the enemy to the attack method using the & or * symbol when writing the parameter (note if you use * it gets the memory address so you would have to use -> instead of . to access the enemy's members), so it would look like this: ReturnType FunctionName(Type ¶mName). For example:
c++:
#include <iostream>
usingnamespace std;
void Increment(int &someNumber) {
someNumber++;
}
int main() { int num = 5;
cout << num << "\n";
Increment(num);
cout << num << "\n";
system("PAUSE");
return0;
}
If you do not yet know pointers let me point you to (get it?) a good tutorial. Or for more visual learners, an awesome youtube video that either Dan or Tony posted sometime within the last week or two.
Of course if for whatever reason enemy is the class and gethurt is a static method, than you can call it like you have shown (just make sure you #include it in the header file)