
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
How to write a singleton class in C++?
Singleton design pattern is a software design principle that is used to restrict the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. For example, if you are using a logger, that writes logs to a file, you can use a singleton class to create such a logger. You can create a singleton class using the following code.
Example
#include <iostream> using namespace std; class Singleton { static Singleton *instance; int data; // Private constructor so that no objects can be created. Singleton() { data = 0; } public: static Singleton *getInstance() { if (!instance) instance = new Singleton; return instance; } int getData() { return this -> data; } void setData(int data) { this -> data = data; } }; //Initialize pointer to zero so that it can be initialized in first call to getInstance Singleton *Singleton::instance = 0; int main(){ Singleton *s = s->getInstance(); cout << s->getData() << endl; s->setData(100); cout << s->getData() << endl; return 0; }
Output
0 100
- Related Articles
- How to use singleton class in android?
- How to make a class singleton in Java?\n
- Singleton Class in C#
- How to prevent Cloning to break a Singleton Class Pattern?
- How to prevent Reflection to break a Singleton Class Pattern?
- How to prevent Serialization to break a Singleton Class Pattern?
- How to prevent Cloning to break a Singleton Class Pattern in Java?
- What is a singleton class in Java?
- How to refresh Singleton class every one hour in android?
- How we can create singleton class in Python?
- Why singleton class is always sealed in C#?
- How to make a singleton enum in Java?
- How to implement a Singleton design pattern in C#?
- How to write a class inside an interface in Java?
- How to clear Singleton instance in android?

Advertisements