CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Aug 2009

    When to use static classes


    I am just wondering what the best practice is for when to use static classes (by static class, I mean a class which has only static attributes and functions).

    If you are creating more than one independent object of a particular class, then obviously this should not be static because each object will be the same. But what about the case when you know that you will only ever need one instance of a class? On its own, does this mean that you should create it as a static class?

    Personally, I use static class when I want its member attributes and functions to be available globally, which I think is fine. However, I am not sure about the case when I know that only one object will be created - should this be a static class or not?


  2. #2
    Join Date
    May 2009

    Re: When to use static classes

    Quote Originally Posted by karnavor View Post
    I am just wondering what the best practice is for when to use static classes
    The general consensus is as little as possible. The idea is that global shared data is bad because it induces dependencies in designs.

    Nevertheless, there's a design pattern to handle the one global object situation and it's called the Singleton. Many have taken the very existence of Singleton as cue to use it extensively but design pattern or not, global data still is global data and it's better to avoid it.

    On the other hand if you have a bunch of stateless global functions that belong together logically, of course you can make them static and keep them in a class. That's what you would do in Java (see for example the Math class). In C++ you can as well use free functions in a namespace.
    Last edited by nuzzle; May 3rd, 2013 at 01:52 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Windows Mobile Development Center

Click Here to Expand Forum to Full Width

On-Demand Webinars (sponsored)