-6

I just realised I made a class member static unnecessarily. I wondered whether it made sense, or what the difference is between them. So I have:

struct Log
{
    int a;
    std::string text;
};

struct GUI
{
    GUI() = delete;
    static void doSomething() {}
    static inline int a;
    static inline Foo fooObj;
};

or

struct GUI2
{
    GUI2() = delete;
    static void doSomething() {}
    int a;
    Foo fooObj;
};

So you can see that this GUI class is always going to be accessed with the scope operator GUI:: instead of the dot member operator, I won't be creating any instances of it, it's completely static. So the int and the Foo object in the two GUI classes either have the "static" keyword or not. In the case where the GUI classes won't be instantiated I don't believe this will make a difference. As a matter of best practice is it better to leave the static keyword out? Also, what if any difference is there between the two? I just noticed I think it makes no difference in my case.

Zebrafish
  • 11,682
  • 3
  • 43
  • 119
  • @Ron I made the Foo and int member objects in GUI class static, when GUI is a static class itself, is static in that case not necessary? And is there any difference? – Zebrafish Jun 07 '18 at 14:48
  • There is no such thing as a _static class_ in C++. – Ron Jun 07 '18 at 14:50
  • If you are not going to create any instances of it, why make it a class at all? Just use a namespace. – CodingLumis Jun 07 '18 at 14:54
  • @CodingLumis It gives me access specifiers, and... I can't remember what else, I tossed up whether to use namespace or class, I decided on class. – Zebrafish Jun 07 '18 at 14:56

1 Answers1

3
struct GUI2
{
    GUI2() = delete;
    static void doSomething() {}
    int a;
    Foo fooObj;
};

int main() {
    GUI2::a = 0; // error
}

If GUI2::a is not a static member, it exists only in the GUI objects. This means it cannot be accessed with GUI2::a since no instance of a is attached to the class. You would need an instance:

GUI2 gui;
gui.a = 0; // OK

If GUI2::a is a static member, it is dissociated with the objects and exists independently (and must be defined as such with int GUI::a; somewhere):

GUI2::A = 0; // OK

Does the “static” keyword in these examples make a difference?

Yes it does.

Ron
  • 14,674
  • 4
  • 34
  • 47
YSC
  • 38,212
  • 9
  • 96
  • 149
  • Ah, I got confused, of course it makes a difference. I'd spent a long time away and forgotten the rules. I do indeed need to make it static. – Zebrafish Jun 07 '18 at 14:53