C++ Gurus

Jason Wright jason at thought.net
Fri Feb 22 22:45:59 CST 2013


On Fri, Feb 22, 2013 at 4:11 PM, Karl W4KRL <W4KRL at arrl.net> wrote:

> Jason,****
>
> ** **
>
> I think that is pretty much what I am looking for. I will give it a try.
> If a variable is, say, public: int var then each object will have its own
> var. But if it is private: static int var then if var changes in the class
> it will change in all objects? How do I implement a method that will change
> the class variable?****
>
> **
>

Let's take the following example:

class foo {
  private: int x;
  private: static int y;

  public:
    void set_x(int newx) { x = newx; };
    void set_y(int newy) { y = newy; };
    int get_x(void) { return x; };
    int get_y(void) { return y; };
};

// note: the definition below must occur in exactly one place
// (a c++ file, not a header).  Failure to include it will get you undefined
// reference; including it in a header that's used in several places will
// buy you "multiply defined" errors.
// this is the line that actually allocates space for
// the global (class) variable)
int foo:y;

int
main() {
   foo f1, f2;

  f1.set_x(1);
  f2.set_x(2);
  f1.set_y(1);
  f2.set_y(2);

  cout << "f1's X: " << f1.get_x() << endl;
  cout << "f2's X: " << f2.get_x() << endl;
  cout << "f2's Y: " << f1.get_y() << endl;
  cout << "f2's Y: " << f2.get_y() << endl;
}

produces:

f1's X: 1
f2's X: 2
f1's Y: 2
f2's Y: 2

What's going on here is that foo has an instance variable (x) which is
allocated uniquely for each instance, and a class variable (y) which is
global. References to (x) use the instance variable particular to the
current instance, but all references to (y) by any instance all refer to
the same chunk of memory.  I.e. there are many x's (once for each instance)
and exactly one (y) (shared by all instances).

--Jason L. Wright
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://amrad.org/pipermail/tacos/attachments/20130222/ecdba2cf/attachment-0001.html>


More information about the Tacos mailing list