How would I call this function?

I have a header file and a main file. I want to call the "HP" value that is inside my header file, but how would I do this? Here is the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
//HEADERFILE
class mage{
public:
	mage(){
	hp = 100;
	}

	int getHP(){
		return hp;
	}
	
private:int hp;
};

1
2
3
4
//MAIN FILE
void funtion(){
cout << "HP: " << //trying to call function getHP from here
}
You can't call a member function unless you have an object.

For instance, your mage class represents a single mage. But you could have multiple mages. Let's say you want to have 2 mages, Jeff and Bill:

1
2
3
4
5
6
7
8
9
10
mage Jeff;
mage Bill;

// now let's say Jeff has more hit points
Jeff.setHP(150);  // (assuming this function exists)


// now you can get each mage's hit points:
cout << "Bill's HP: " << Bill.getHP() << "\n";  // outputs 100 because Bill has 100 HP
cout << "Jeff's HP: " << Jeff.getHP() << "\n";  // outputs 150 because Jeff has 150 HP 


Unless you have an object (a mage) on which to call this function, calling the function makes no sense. Whose HP are you getting?
Last edited on
Topic archived. No new replies allowed.