Pages: [1]   Go Down
Author Topic: global variable for multiple objects?  (Read 447 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 0
Posts: 24
Dont think like a computer, make it think like you
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

i've created a couple objects:

Code:
 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
Logged

Florida, USA
Offline Offline
Full Member
***
Karma: 0
Posts: 146
meow!
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Code:
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
Logged

Pages: [1]   Go Up
Jump to: