Calling Global Variables

Recently I asked how to call variables in other classes. The answer revolved around setting the values and just retrieving that value. My question now revolves around global variables.

first.cpp
1
2
3
4
5
6
7
 #include<iostream>
using namespace std;

extern int initial;
int main(){
cout << "What is your first initial?" <<endl;
cin >> initial;


how would I call that in a another .cpp file?
http://www.learncpp.com/cpp-tutorial/42-global-variables/

Note: it is usually better to avoid global variables.
Why is that?
Im still having trouble using different classes and variables throughout. For example If I have a health variable in class pirate. I want to use an if statement if for the health variable in class monk. How would I go about that?
you can use the following logic:-

declare the same variable in the other class and initiate it to 0. now check its value, if the value is same as you entered through the code you shown then the variable exists otherwise not
You could provide various functions to retrieve the health statistics. For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// An interface
class Entity {
    public:
        virtual ~Entity() {}

        virtual void getHP() const = 0;   // Get the current HP of the entity
        virtual void takeDamage(int dmg) = 0;
        virtual void attack(Entity* other) = 0;

        // other common functions
};

// Pirate class
class Pirate : public Entity {
    public:
        Pirate() : _hp(20) {}
        virtual ~Pirate() {}
    
        virtual void getHP() const override { return _hp; }
        virtual void takeDamage(int dmg) { _hp -= dmg; }
        virtual void attack(Entity* other) { other->takeDamage(5); }

    protected:
        int _hp;
};

// Monk class
class Monk : public Entity {
    public:
        Monk() : _hp(50) {}
        virtual ~Monk() {}
    
        virtual void getHP() const override { return _hp; }
        virtual void takeDamage(int dmg) { _hp -= dmg; }
        virtual void attack(Entity* other) { other->takeDamage(2); }

    protected:
        int _hp;
};

// ...

Entity* pirate = new Pirate;
Entity* monk = new Monk;

if (monk->getHP() < pirate->getHP()) {
    // ...
}


Note that this is just an example - for doing what I have there, there are better ways (such as data orientation), but I'm just putting this around what you have said so far.
Topic archived. No new replies allowed.