global variable for multiple objects?

i've created a couple objects:

  Button recBtn = Button(7);
  Button playBtn = Button(8);

What would need to be done to create a global variable shared by both objects? Make them subclasses rather than classes? Can anyone point me to an example?


A good way to share variables between instances of a class in C++ is to make them static. For example:

class Button {
    // blah blah blah...

    int  fred;
    static int barney;

int Button::barney = 17;

Button recBtn = Button(7);
Button playBtn = Button(8);

In this contrived example, recBtn and playBtn each have their own, independent copy of “fred”, but they share a single copy of “barney”. Note that you must declare each static variable inside the class, and define them outside the class. Hope this helps.

  • Don