1

I have a question about static member of class in c++, since the static member belongs to the class not any instance of class, so should the static member be declared as public, private?

0

3 Answers 3

8

Whether or not to declare a member public or private has nothing to do with whether it is static or not. You can have a static member be either public or private; both uses are acceptable depending on the situation.

Basically, if you want or need components outside of the class to have direct access to the static member, make it public. Otherwise, make it private.

Sign up to request clarification or add additional context in comments.

Comments

2

Actually the static member is shared by all instances of the class. If it was a data member for example you could use is to count how many instances of the class were created. You can declare it either private or public or protected depending on your needs.

Comments

0

You're talking about making some static class members private to the class, so that instances of the class can't access them. Unfortunately I don't think c++ has any syntactical mechanism that you can use to enforce that at compile time. You might be able to pull off a runtime check, but it would be convoluted to say the least.

Really, I'm not sure why you would want to do what your asking. If you are already in ownership of and editing the class, you are also able to edit all the instance methods to ensure they don't use the static member. If you want to try to enforce it you'll have to put a big heavy comment next to your static member saying "Instance methods shouldn't use this" and make sure your team knows it. In general, you don't have to be religious about accessor modifiers like public/private in order to write good code so I would simply say don't worry about trying to enforce what you suggested.

Other object-oriented languages could provide what you are asking for as they draw more of distinction between classes and instances. e.g. Scala, Smalltalk.

Comments