-1

I'm writing a utility application in a procedural object-oriented style by building modules as storage classes.

Using the following approach:

class A
{
    public:
       static int foo;
};

class B
{
    public:
       static A bar;
};

class C
{
    public:
       A bar;
};

What is the difference between the behavior of classes B and C?

Edit: What differs in the life-time of storage class A when declared static in class B as to when declared non-static in class C?

YSC
  • 38,212
  • 9
  • 96
  • 149
athereos
  • 1
  • 1
  • 3
    [Inside a class definition, the keyword static declares members that are not bound to class instances.](https://en.cppreference.com/w/cpp/language/static) – Ted Lyngmo Apr 24 '19 at 14:06
  • 2
    related/dupe: https://stackoverflow.com/questions/15235526/the-static-keyword-and-its-various-uses-in-c – NathanOliver Apr 24 '19 at 14:11
  • 2
    Any [good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282) should explain the difference between a static and a non-static member. – Some programmer dude Apr 24 '19 at 14:12
  • 1
    Possible duplicate of [The static keyword and its various uses in C++](https://stackoverflow.com/questions/15235526/the-static-keyword-and-its-various-uses-in-c) – Ted Lyngmo Apr 24 '19 at 14:12

1 Answers1

0

Class B declares a static member A of the class B, which means that it is not bound to class instances, but accessible by all instances of the class. Each instance can update it and the other instances will see the update.

Class C declares a non-static member A of the class C, which means that it is bound to the instance of the class. Each instance has its own Class A member. Modifying one will not affect the others.

As A is public in both Class B and Class C, anyone can access the Class A object according to the rules described.

Incidentally, as foo is declared static, foo is not bound to any instance of Class A. So, even though C contains a non-static A, foo itself will be static and accessible through any instance of B or C.

Gardener
  • 2,591
  • 1
  • 13
  • 22