Advertisement
STANAANDREY

inherited single

Feb 10th, 2023
888
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.69 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. template <typename T>
  5. class Singleton
  6. {
  7. protected:
  8.     static T* instance;
  9.     Singleton() {}
  10.     Singleton(const Singleton&);
  11.     Singleton& operator=(const Singleton&);
  12.  
  13. public:
  14.     static T* getInstance()
  15.     {
  16.         if (!instance)
  17.             instance = new T();
  18.         return instance;
  19.     }
  20. };
  21.  
  22. template <typename T>
  23. T* Singleton<T>::instance = nullptr;
  24.  
  25. class MyClass : public Singleton<MyClass>
  26. {
  27. public:
  28.     MyClass(){}
  29.     string name;
  30. };
  31.  
  32.  
  33. int main() {
  34.  
  35.     MyClass *mc = nullptr;
  36.     mc = MyClass::getInstance();
  37.     mc->name = "andrew";
  38.     MyClass *oc = mc;
  39.     cout << oc->name << endl;
  40.     return 0;
  41. }
  42.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement