1

I inherited a project from a former colleague, and I found these code snippets (and some similar ones in SO questions: can a c++ class include itself as an member and static member object of a class in the same class)

// Service.h
class Service
{
// ...
public:
    static Service sInstance;
    void Somememberfunc();
//...
};

// Service.cpp
#include "Service.h"

Service Service::sInstance;

void Service::Somememberfunc()
{
//...
}

// Main.cpp
#include "Service.h"
void Fun()
{
    Service &instance = Service::sInstance;
    //...
    instance.Somememberfunc();
    //...
}

However, I did not find any explanation on when to use this pattern. And what are the advantages and disadvantages?

Jarod42
  • 203,559
  • 14
  • 181
  • 302
DerekLu
  • 79
  • 2
  • 7

4 Answers4

3

Notice that the member is a static, so it's part of the class, not of instantiated objects. This is important, because otherwise you would be trying to make a recursive member (since the member is part of the object, it also contains the same member and so on...), but this is not the case here.

The best pattern to describe this is: global variable. The static member is initialized before main() and can be accessed from any part of the program by including the header file. This is very convenient while implementing but becomes harder to handle the more complex the program gets and the longer you have to maintain it, so the general idea is to avoid this. Also, because there is no way to control the order of initialization, dependencies between different global variables can cause problems during startup.

stefaanv
  • 14,072
  • 2
  • 31
  • 53
  • 1
    Thanks for your reply. Can I say that this pattern is similar to static class in c# if the constructor is private. – DerekLu Mar 17 '21 at 16:46
1

Static member is roughly a global variable in the scope of the class.

Static members have also the advantage of visibility access (public/protected/private) to restreint its usage (file scope might be an alternative).

That member might be of type of the class.

Global are "easy" to (mis)use, as they don't require to think about architecture.

BUT (mutable) global are mostly discouraged as harder to reason about.

Acceptable usages IMO are for constants:

  • as for a matrix class, the null matrix, the diagonal one matrix.
  • for Temperature class, some specific value (absolute 0 (O Kelvin), temperature of water transformation(0 Celsius, 100 Celsius), ...)
  • in general NullObject, Default, ...
Jarod42
  • 203,559
  • 14
  • 181
  • 302
0

Singleton pattern. For example, you can use it to store your app configurations. And then you can easily access configurations anywhere(globally) within your app.

Allen ZHU
  • 690
  • 5
  • 14
-1

This is often used in the singleton design pattern Visit https://en.wikipedia.org/wiki/Singleton_pattern

yair koskas
  • 134
  • 5