<p>How do you create a static class in C++? I should be able to do something like:</p>

<pre><code>cout &lt;&lt; "bit 5 is " &lt;&lt; BitParser::getBitAt(buffer, 5) &lt;&lt; endl;
</code></pre>

<p>Assuming I created the <code>BitParser</code> class. What would the <code>BitParser</code> class definition look like?</p>

[{'answer_id': 9326, 'author': 'Philip Reynolds', 'author_id': 1087, 'author_profile': 'https://Stackoverflow.com/users/1087', 'pm_score': 4, 'selected': False, 'text': '<p>In C++ you want to create a static function of a class (not a static class).</p>\n\n<pre><code>class BitParser {\npublic:\n  ...\n  static ... getBitAt(...) {\n  }\n};\n</code></pre>\n\n<p>You should then be able to call the function using BitParser::getBitAt() without instantiating an object which I presume is the desired result.</p>\n'}, {'answer_id': 9328, 'author': 'OJ.', 'author_id': 611, 'author_profile': 'https://Stackoverflow.com/users/611', 'pm_score': 9, 'selected': True, 'text': "<p>If you're looking for a way of applying the &quot;static&quot; keyword to a class, like you can in C# for example, then you won't be able to without using Managed C++.</p>\n<p>But the looks of your sample, you just need to create a public static method on your BitParser object. Like so:</p>\n<p><strong>BitParser.h</strong></p>\n<pre><code>class BitParser\n{\n public:\n  static bool getBitAt(int buffer, int bitIndex);\n\n  // ...lots of great stuff\n\n private:\n  // Disallow creating an instance of this object\n  BitParser() {}\n};\n</code></pre>\n<p><strong>BitParser.cpp</strong></p>\n<pre><code>bool BitParser::getBitAt(int buffer, int bitIndex)\n{\n  bool isBitSet = false;\n  // .. determine if bit is set\n  return isBitSet;\n}\n</code></pre>\n<p>You can use this code to call the method in the same way as your example code.</p>\n"}, {'answer_id': 9339, 'author': 'Orion Edwards', 'author_id': 234, 'author_profile': 'https://Stackoverflow.com/users/234', 'pm_score': 4, 'selected': False, 'text': '<blockquote>\n  <p>If you\'re looking for a way of applying the "static" keyword to a class, like you can in C# for example</p>\n</blockquote>\n\n<p>static classes are just the compiler hand-holding you and stopping you from writing any instance methods/variables.</p>\n\n<p>If you just write a normal class without any instance methods/variables, it\'s the same thing, and this is what you\'d do in C++</p>\n'}, {'answer_id': 9348, 'author': 'Matt Price', 'author_id': 852, 'author_profile': 'https://Stackoverflow.com/users/852', 'pm_score': 6, 'selected': False, 'text': "<p>You can also create a free function in a namespace:</p>\n\n<p>In BitParser.h</p>\n\n<pre><code>namespace BitParser\n{\n    bool getBitAt(int buffer, int bitIndex);\n}\n</code></pre>\n\n<p>In BitParser.cpp</p>\n\n<pre><code>namespace BitParser\n{\n    bool getBitAt(int buffer, int bitIndex)\n    {\n        //get the bit :)\n    }\n}\n</code></pre>\n\n<p>In general this would be the preferred way to write the code. When there's no need for an object don't use a class.</p>\n"}, {'answer_id': 112451, 'author': 'paercebal', 'author_id': 14089, 'author_profile': 'https://Stackoverflow.com/users/14089', 'pm_score': 8, 'selected': False, 'text': '<p>Consider <a href="https://stackoverflow.com/questions/9321/how-do-you-create-a-static-class-in-c/9348#9348">Matt Price\'s solution</a>.</p>\n\n<ol>\n<li>In C++, a "static class" has no meaning. The nearest thing is a class with only static methods and members.</li>\n<li>Using static methods will only limit you.</li>\n</ol>\n\n<p>What you want is, expressed in C++ semantics, to put your function (for it <strong>is</strong> a function) in a namespace.</p>\n\n<h2>Edit 2011-11-11</h2>\n\n<p>There is no "static class" in C++. The nearest concept would be a class with only static methods. For example:</p>\n\n<pre><code>// header\nclass MyClass\n{\n   public :\n      static void myMethod() ;\n} ;\n\n// source\nvoid MyClass::myMethod()\n{\n   // etc.\n}\n</code></pre>\n\n<p>But you must remember that "static classes" are hacks in the Java-like kind of languages (e.g. C#) that are unable to have non-member functions, so they have instead to move them inside classes as static methods.</p>\n\n<p>In C++, what you really want is a non-member function that you\'ll declare in a namespace:</p>\n\n<pre><code>// header\nnamespace MyNamespace\n{\n   void myMethod() ;\n}\n\n// source\nnamespace MyNamespace\n{\n   void myMethod()\n   {\n      // etc.\n   }\n}\n</code></pre>\n\n<h3>Why is that?</h3>\n\n<p>In C++, the namespace is more powerful than classes for the "Java static method" pattern, because:</p>\n\n<ul>\n<li>static methods have access to the classes private symbols</li>\n<li>private static methods are still visible (if inaccessible) to everyone, which breaches somewhat the encapsulation</li>\n<li>static methods cannot be forward-declared</li>\n<li>static methods cannot be overloaded by the class user without modifying the library header</li>\n<li>there is nothing that can be done by a static method that can\'t be done better than a (possibly friend) non-member function in the same namespace</li>\n<li>namespaces have their own semantics (they can be combined, they can be anonymous, etc.)</li>\n<li>etc.</li>\n</ul>\n\n<p>Conclusion: Do not copy/paste that Java/C#\'s pattern in C++. In Java/C#, the pattern is mandatory. But in C++, it is bad style.</p>\n\n<h2>Edit 2010-06-10</h2>\n\n<p>There was an argument in favor to the static method because sometimes, one needs to use a static private member variable.</p>\n\n<p>I disagree somewhat, as show below:</p>\n\n<h3>The "Static private member" solution</h3>\n\n<pre><code>// HPP\n\nclass Foo\n{\n   public :\n      void barA() ;\n   private :\n      void barB() ;\n      static std::string myGlobal ;\n} ;\n</code></pre>\n\n<p>First, myGlobal is called myGlobal because it is still a global private variable. A look at the CPP source will clarify that:</p>\n\n<pre><code>// CPP\nstd::string Foo::myGlobal ; // You MUST declare it in a CPP\n\nvoid Foo::barA()\n{\n   // I can access Foo::myGlobal\n}\n\nvoid Foo::barB()\n{\n   // I can access Foo::myGlobal, too\n}\n\nvoid barC()\n{\n   // I CAN\'T access Foo::myGlobal !!!\n}\n</code></pre>\n\n<p>At first sight, the fact the free function barC can\'t access Foo::myGlobal seems a good thing from an encapsulation viewpoint... It\'s cool because someone looking at the HPP won\'t be able (unless resorting to sabotage) to access Foo::myGlobal.</p>\n\n<p>But if you look at it closely, you\'ll find that it is a colossal mistake: Not only your private variable must still be declared in the HPP (and so, visible to all the world, despite being private), but you must declare in the same HPP all (as in ALL) functions that will be authorized to access it !!!</p>\n\n<p>So <b>using a private static member is like walking outside in the nude with the list of your lovers tattooed on your skin : No one is authorized to touch, but everyone is able to peek at. And the bonus: Everyone can have the names of those authorized to play with your privies.</b></p>\n\n<p><code>private</code> indeed...\n:-D</p>\n\n<h3>The "Anonymous namespaces" solution</h3>\n\n<p>Anonymous namespaces will have the advantage of making things private really private.</p>\n\n<p>First, the HPP header</p>\n\n<pre><code>// HPP\n\nnamespace Foo\n{\n   void barA() ;\n}\n</code></pre>\n\n<p>Just to be sure you remarked: There is no useless declaration of barB nor myGlobal. Which means that no one reading the header knows what\'s hidden behind barA.</p>\n\n<p>Then, the CPP:</p>\n\n<pre><code>// CPP\nnamespace Foo\n{\n   namespace\n   {\n      std::string myGlobal ;\n\n      void Foo::barB()\n      {\n         // I can access Foo::myGlobal\n      }\n   }\n\n   void barA()\n   {\n      // I can access myGlobal, too\n   }\n}\n\nvoid barC()\n{\n   // I STILL CAN\'T access myGlobal !!!\n}\n</code></pre>\n\n<p>As you can see, like the so-called "static class" declaration, fooA and fooB are still able to access myGlobal. But no one else can. And no one else outside this CPP knows fooB and myGlobal even exist!</p>\n\n<p><b>Unlike the "static class" walking on the nude with her address book tattooed on her skin the "anonymous" namespace is fully clothed</b>, which seems quite better encapsulated AFAIK.</p>\n\n<h3>Does it really matter?</h3>\n\n<p>Unless the users of your code are saboteurs (I\'ll let you, as an exercise, find how one can access to the private part of a public class using a dirty behaviour-undefined hack...), what\'s <code>private</code> is <code>private</code>, even if it is visible in the <code>private</code> section of a class declared in a header.</p>\n\n<p>Still, if you need to add another "private function" with access to the private member, you still must declare it to all the world by modifying the header, which is a paradox as far as I am concerned: <b>If I change the implementation of my code (the CPP part), then the interface (the HPP part) should NOT change.</b> Quoting Leonidas : "<b>This is ENCAPSULATION!</b>"</p>\n\n<h2>Edit 2014-09-20</h2>\n\n<p>When are classes static methods are actually better than namespaces with non-member functions?</p>\n\n<p>When you need to group together functions and feed that group to a template:</p>\n\n<pre><code>namespace alpha\n{\n   void foo() ;\n   void bar() ;\n}\n\nstruct Beta\n{\n   static void foo() ;\n   static void bar() ;\n};\n\ntemplate &lt;typename T&gt;\nstruct Gamma\n{\n   void foobar()\n   {\n      T::foo() ;\n      T::bar() ;\n   }\n};\n\nGamma&lt;alpha&gt; ga ; // compilation error\nGamma&lt;Beta&gt; gb ;  // ok\ngb.foobar() ;     // ok !!!\n</code></pre>\n\n<p>Because, if a class can be a template parameter, a namespaces cannot.</p>\n'}, {'answer_id': 1785945, 'author': 'Netzer', 'author_id': 217347, 'author_profile': 'https://Stackoverflow.com/users/217347', 'pm_score': 3, 'selected': False, 'text': "<p>You 'can' have a static class in C++, as mentioned before, a static class is one that does not have any objects of it instantiated it.  In C++, this can be obtained by declaring the constructor/destructor as private.  End result is the same.</p>\n"}, {'answer_id': 2715977, 'author': 'John', 'author_id': 326261, 'author_profile': 'https://Stackoverflow.com/users/326261', 'pm_score': 2, 'selected': False, 'text': '<p>This is similar to C#\'s way of doing it in C++</p>\n\n<p>In C# file.cs you can have private var inside a public function.\nWhen in another file you can use it by calling the namespace with the function as in:</p>\n\n<pre><code>MyNamespace.Function(blah);\n</code></pre>\n\n<p>Here\'s how to imp the same in C++:</p>\n\n<p><strong>SharedModule.h</strong></p>\n\n<pre><code>class TheDataToBeHidden\n{\n  public:\n    static int _var1;\n    static int _var2;\n};\n\nnamespace SharedData\n{\n  void SetError(const char *Message, const char *Title);\n  void DisplayError(void);\n}\n</code></pre>\n\n<p><strong>SharedModule.cpp</strong></p>\n\n<pre><code>//Init the data (Link error if not done)\nint TheDataToBeHidden::_var1 = 0;\nint TheDataToBeHidden::_var2 = 0;\n\n\n//Implement the namespace\nnamespace SharedData\n{\n  void SetError(const char *Message, const char *Title)\n  {\n    //blah using TheDataToBeHidden::_var1, etc\n  }\n\n  void DisplayError(void)\n  {\n    //blah\n  }\n}\n</code></pre>\n\n<hr>\n\n<p><strong>OtherFile.h</strong></p>\n\n<pre><code>#include "SharedModule.h"\n</code></pre>\n\n<p><strong>OtherFile.cpp</strong></p>\n\n<pre><code>//Call the functions using the hidden variables\nSharedData::SetError("Hello", "World");\nSharedData::DisplayError();\n</code></pre>\n'}, {'answer_id': 3015915, 'author': 'Malc B', 'author_id': 363621, 'author_profile': 'https://Stackoverflow.com/users/363621', 'pm_score': 2, 'selected': False, 'text': '<p>In Managed C++, static class syntax is:-</p>\n\n<pre><code>public ref class BitParser abstract sealed\n{\n    public:\n        static bool GetBitAt(...)\n        {\n            ...\n        }\n}\n</code></pre>\n\n<p>... better late than never...</p>\n'}, {'answer_id': 21423774, 'author': 'Bharath Ravindra', 'author_id': 2022210, 'author_profile': 'https://Stackoverflow.com/users/2022210', 'pm_score': 2, 'selected': False, 'text': '<p>Unlike other managed programming language, "static class" has NO meaning in C++. You can make use of static member function. </p>\n'}, {'answer_id': 31201984, 'author': 'Ciro Santilli OurBigBook.com', 'author_id': 895245, 'author_profile': 'https://Stackoverflow.com/users/895245', 'pm_score': 4, 'selected': False, 'text': '<p><strong>Can I write something like <code>static class</code>?</strong></p>\n\n<p><strong>No</strong>, according to the <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf" rel="nofollow noreferrer">C++11 N3337 standard draft</a> Annex C 7.1.1:</p>\n\n<blockquote>\n  <p>Change: In C ++, the static or extern specifiers can only be applied to names of objects or functions.\n  Using these specifiers with type declarations is illegal in C ++. In C, these specifiers are ignored when used\n  on type declarations. Example:</p>\n\n<pre><code>static struct S {    // valid C, invalid in C++\n  int i;\n};\n</code></pre>\n  \n  <p>Rationale: Storage class specifiers don’t have any meaning when associated with a type. In C ++, class\n  members can be declared with the static storage class specifier. Allowing storage class specifiers on type\n  declarations could render the code confusing for users.</p>\n</blockquote>\n\n<p>And like <code>struct</code>, <code>class</code> is also a type declaration.</p>\n\n<p>The same can be deduced by walking the syntax tree in Annex A.</p>\n\n<p>It is interesting to note that <code>static struct</code> was legal in C, but had no effect: <a href="https://stackoverflow.com/questions/7259830/why-and-when-to-use-static-structures-in-c-programming">Why and when to use static structures in C programming?</a></p>\n'}, {'answer_id': 49405640, 'author': 'Mikhail Vasilyev', 'author_id': 4432988, 'author_profile': 'https://Stackoverflow.com/users/4432988', 'pm_score': 3, 'selected': False, 'text': "<p>As it has been noted here, a better way of achieving this in C++ might be using namespaces. But since no one has mentioned the <code>final</code> keyword here, I'm posting what a direct equivalent of <code>static class</code> from C# would look like in C++11 or later:</p>\n\n<pre><code>class BitParser final\n{\npublic:\n  BitParser() = delete;\n\n  static bool GetBitAt(int buffer, int pos);\n};\n\nbool BitParser::GetBitAt(int buffer, int pos)\n{\n  // your code\n}\n</code></pre>\n"}, {'answer_id': 50016722, 'author': 'Josh Olson', 'author_id': 9209968, 'author_profile': 'https://Stackoverflow.com/users/9209968', 'pm_score': 0, 'selected': False, 'text': '<p>One case where namespaces may not be so useful for achieving "static classes" is when using these classes to achieve composition over inheritance. Namespaces cannot be friends of classes and so cannot access private members of a class.</p>\n\n<pre><code>class Class {\n public:\n  void foo() { Static::bar(*this); }    \n\n private:\n  int member{0};\n  friend class Static;\n};    \n\nclass Static {\n public:\n  template &lt;typename T&gt;\n  static void bar(T&amp; t) {\n    t.member = 1;\n  }\n};\n</code></pre>\n'}, {'answer_id': 61626014, 'author': 'hecate', 'author_id': 6426767, 'author_profile': 'https://Stackoverflow.com/users/6426767', 'pm_score': 2, 'selected': False, 'text': '<p>One (of the many) alternative, but the most (in my opinion) elegant (in comparison to using namespaces and private constructors to emulate the static behavior), way to achieve the "class that cannot be instantiated" behavior in C++ would be to declare a dummy pure virtual function with the <code>private</code> access modifier.</p>\n\n<pre><code>class Foo {\n   public:\n     static int someMethod(int someArg);\n\n   private:\n     virtual void __dummy() = 0;\n};\n</code></pre>\n\n<p>If you are using C++11, you could go the extra mile to ensure that the class is not inherited (to purely emulate the behavior of a static class) by using the <code>final</code> specifier in the class declaration to restrict the other classes from inheriting it.</p>\n\n<pre><code>// C++11 ONLY\nclass Foo final {\n   public:\n     static int someMethod(int someArg);\n\n   private:\n      virtual void __dummy() = 0;\n};\n</code></pre>\n\n<p>As silly and illogical as it may sound, C++11 allows the declaration of a "pure virtual function that cannot be overridden", which you can use alongside declaring the class <code>final</code> to purely and fully implement the static behavior as this results in the resultant class to not be inheritable and the dummy function to not be overridden in any way.</p>\n\n<pre><code>// C++11 ONLY\nclass Foo final {\n   public:\n     static int someMethod(int someArg);\n\n   private:\n     // Other private declarations\n\n     virtual void __dummy() = 0 final;\n}; // Foo now exhibits all the properties of a static class\n</code></pre>\n'}, {'answer_id': 66422537, 'author': 'Саша Зезюлинский', 'author_id': 857684, 'author_profile': 'https://Stackoverflow.com/users/857684', 'pm_score': 0, 'selected': False, 'text': "<pre><code>class A final {\n  ~A() = delete;\n  static bool your_func();\n}\n</code></pre>\n<p><code>final</code> means that a class cannot be inherited from.</p>\n<p><code>delete</code> for a destructor means that you can not create an instance of such a class.</p>\n<p>This pattern is also know as an &quot;util&quot; class.</p>\n<p>As many say the concept of <code>static class</code> doesn't exist in C++.</p>\n<p>A canonical <code>namespace</code> that contains <code>static</code> functions preferred as a solution in this case.</p>\n"}, {'answer_id': 68140352, 'author': 'Sarath Govind', 'author_id': 12284466, 'author_profile': 'https://Stackoverflow.com/users/12284466', 'pm_score': 0, 'selected': False, 'text': '<p>There is no such thing as a static class in C++. The closest approximation is a class that only contains static data members and static methods.\nStatic data members in a class are shared by all the class objects as there is only one copy of them in memory, regardless of the number of objects of the class.\nA static method of a class can access all other static members ,static methods and methods outside the class</p>\n'}]
['https://Stackoverflow.com/questions/9321', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/432/']