Go Down

Topic: global variable for multiple objects? (Read 493 times) previous topic - next topic

Gabe462

i've created a couple objects:

Code: [Select]
 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?

Gabe

CosineKitty

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

Code: [Select]

class Button {
public:
   // blah blah blah...

private:
   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

Go Up