1

When we implement static int member, I usually do like this

class A {
  public:
  static int a = 5;
};

But once I found the code below, that enables the same thing, I noticed that we can access the member through A::a. I prefer this because initialization before the main function is not needed as opposed to the static int

class A {
  public:
    enum { a = 5 };
};
    

Which one is better? Is there any benefit of using static int??

mallea
  • 534
  • 6
  • 17
  • 2
    What version of C++ can you use? In C++17 `static int a = 5;` can be `inline static int a = 5;` – NathanOliver Jun 29 '20 at 14:31
  • Don't declare class variables as public, it violates the rule of OOP. – Rohan Bari Jun 29 '20 at 14:32
  • 4
    Do you mean `static const int` or `static constexpr int`? Your current code would have `a` be mutable for the first example, whereas the second is constant. – Human-Compiler Jun 29 '20 at 14:32
  • 1
    The benefit of using `static int` is that it is a variable, and can vary when you set it to a different value. – Eljay Jun 29 '20 at 14:34
  • 1
    Did you mean `static const int a`? You're comparing a variable and a constant... My personal preference: `constexpr int a = 5;`. Unscoped enums can trigger linter warnings recommending the use of scoped enum instead. – rustyx Jun 29 '20 at 14:39
  • If you meant `static const` member, then please search; this has been asked and answered already many times. – underscore_d Jun 29 '20 at 14:40
  • 1
    Does this answer your question? [static const Member Value vs. Member enum : Which Method is Better & Why?](https://stackoverflow.com/questions/204983/static-const-member-value-vs-member-enum-which-method-is-better-why) – underscore_d Jun 29 '20 at 14:40

1 Answers1

0

Is there any benefit of using static int?

Yes, in some situations, you need to change the value of the variables for all instances of a same class. That's not possible without the use of static.

Only one copy of static variables are created for all variable numbers of instances of an object & notice that they're only accessible by static member functions, i.e. if you change the value of a static variable somewhere in the class code, it'll be changed for each object of the specified class.

Rohan Bari
  • 7,482
  • 3
  • 14
  • 34
  • They meant any benefit _versus `enum`_. You can never change the value of an enumerator member (in their example, `A::a`), so this comparison is moot and seems irrelevant, like a comparison to non-static member variables instead of enums. – underscore_d Jun 29 '20 at 14:41