Go Down

Topic: global variable for multiple objects? (Read 512 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
 


Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

Arduino
via Egeo 16
Torino, 10131
Italy