Singleton Pattern | C++ Design Patterns (original) (raw)

Last Updated : 18 May, 2026

The Singleton Pattern is a creational design pattern that ensures only one instance of a class exists throughout the application. It also provides a global access point to that instance, helping maintain consistency and controlled resource usage.

#include

class Singleton { private: static Singleton* instance;

// Private constructor
Singleton() {
    std::cout << "Singleton instance created.\n";
}

// Delete copy constructor and assignment
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;

public: static Singleton* getInstance() { if (instance == nullptr) instance = new Singleton(); return instance; }

void showMessage() {
    std::cout << "Hello from Singleton!" << std::endl;
}

};

Singleton* Singleton::instance = nullptr;

int main() { Singleton* s1 = Singleton::getInstance(); s1->showMessage();

Singleton* s2 = Singleton::getInstance();
std::cout << (s1 == s2); // Will print 1 (true)
return 0;

}

`

Output

Singleton instance created. Hello from Singleton! 1

Advantages

The Singleton Pattern provides controlled access to a single shared instance and helps optimize resource usage across the application.

Limitations of Singleton Pattern

Although the Singleton Pattern is useful for controlling object creation, it also has several limitations and should be used carefully.

Common Use Cases

The Singleton Pattern is commonly used for managing shared resources or centralized services.