/* Copyright (C) Aécio Levy * Written by Aécio Levy - 16/03/2018 * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. */ #include "stdafx.h" #include template class Singleton { protected: // Static member variable // The instace will be "stored"" static T* mSingleton; Singleton() {}; virtual ~Singleton() {}; public: // Avoid Copy constructor Singleton(const Singleton& copy) = delete; // Avoid Copy assingment Singleton& operator = (const Singleton& copy) = delete; // Get the instance. If it is NULL create an instance // Otherwise return the instance static T* Instance() { if (mSingleton == nullptr) { mSingleton = new T(); } return mSingleton; } static void DeleteInstance() { delete mSingleton; } }; class Animal : public Singleton { public: void Testing() { std::cout << "Testing member variable" << std::endl; } }; // a static member variable has to be initialized // out of the constructor because they are not // shared by object. They are initialized only once Animal* Singleton::mSingleton = nullptr; int main() { Animal* animal = Animal::Instance(); animal->Testing(); std::cin.get(); Animal::DeleteInstance(); return 0; }