Ways to share variables between classes

Imagine I have a class A and a class B that both depend on the same set of variables. Class A sets the values for the variables and uses them and when it's time, an object of class B is created where functions in class B will use and modify those variables. However, I need the modifications to not stay solely within B but to also be visible outside of the object of B.
Natively, class B would not be able to see any of class A's members. I decided to let class B inherit class A's members using class B : public A. This allows class B to access everything it needs to. Is there a better or more accepted way of doing this?
I'm also a bit confused about another thing. If an object of B is created in such a scenario, won't the object just have its own copy of A's member variables and functions, meaning that any changes will stay only within the B object and will not appear in an object of A?

Are you trying to make class-wide changes that affect all current and future instances of those objects? Then you're prob looking for static variables:

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
#include <iostream>
#include <string>

using namespace std;

class A
{
public:
    A() {}
    virtual ~A() {}

    const string& City()
    {
        return city_;
    }

protected:
    static string city_;
};
string A::city_ = "Madrid";

class B : public A
{
public:
    // Change city of all current and future A's and B's,
    //   since A::city_ is static (across all class)
    void ChangeCity(const string& city)
    {
        city_ = city;
    }
};

int main() 
{
    A a;
    B b;
    cout << a.City() << "  " << b.City() << endl;
    
    b.ChangeCity("Paris");
    cout << a.City() << "  " << b.City() << endl;

    B b2;
    cout << b2.City() << endl;

    return 0;
}


Madrid  Madrid
Paris  Paris
Paris

Just to note, this is also being discussed in the OP's other thread:

http://www.cplusplus.com/forum/beginner/239748/

Last edited on
Topic archived. No new replies allowed.