473,659 Members | 2,965 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Is a C++ Singleton Class that Simple?

7 New Member
I saw a piece of code from a website. It seems to be a simple example for a singleton class. Basically, the author creates an object in the definition of a class, which has the same name as the class. Inside the definition of the class, everything is public. One cannot instantiate another object. Is it that simple to create a singleton class? Is the all-public members in the class good enough in terms of encapsulation?

In the following is the code run successfully:

#include "stdafx.h"
#include<stdio. h>
#include <iostream>
using namespace std;

class singleton
{
public:
void print()
{
printf("hello\n ");
}
int a;
}singleton;

class client : public singleton
{};

int main()
{
// singleton s; // Can define an object before singleton
// singleton singleton;
// singleton b; #cannot define a new object after singleton
singleton.a=5;
printf("a=%d\n" ,singleton.a);
singleton.print ();

client xyz;
xyz.print();
xyz.a = 10;
cout << "xyz.a = " << xyz.a << endl;

return 0;
}
Jul 24 '07 #1
3 3136
gpraghuram
1,275 Recognized Expert Top Contributor
I saw a piece of code from a website. It seems to be a simple example for a singleton class. Basically, the author creates an object in the definition of a class, which has the same name as the class. Inside the definition of the class, everything is public. One cannot instantiate another object. Is it that simple to create a singleton class? Is the all-public members in the class good enough in terms of encapsulation?

In the following is the code run successfully:

#include "stdafx.h"
#include<stdio. h>
#include <iostream>
using namespace std;

class singleton
{
public:
void print()
{
printf("hello\n ");
}
int a;
}singleton;

class client : public singleton
{};

int main()
{
// singleton s; // Can define an object before singleton
// singleton singleton;
// singleton b; #cannot define a new object after singleton
singleton.a=5;
printf("a=%d\n" ,singleton.a);
singleton.print ();

client xyz;
xyz.print();
xyz.a = 10;
cout << "xyz.a = " << xyz.a << endl;

return 0;
}

Hi,
This is not the right way to create a singleton class and in the example the class name is singleton and not the implementaion is.
Search in thie forum fo singleton class in c++.
Raghuram
Jul 24 '07 #2
plemoine
15 New Member
The singleton is a pattern where you want to make sure that no other instance can be created (you can look at "Effective C++" and "More Effective C++" from Scott Meyers).

Ex.1
Expand|Select|Wrap|Line Numbers
  1. class MySingleton {
  2.   public:
  3.     MySingleton() {
  4.         if (s_pInstance != NULL) {
  5.             //    run-time error
  6.         }
  7.     }
  8.  
  9.     ~MySingleton() {
  10.         if (s_pInstance != NULL) {
  11.             delete s_pInstance;
  12.             s_pInstance = NULL;
  13.         }
  14.     }
  15.  
  16.   private:
  17.     // prevents that an object of the class get copied
  18.     //    ex: MySingleton s2(s1);
  19.     //  ex: s2 = s1;
  20.     MySingleton(const MySingleton&);
  21.     MySingleton& operator=(const MySingleton&);
  22.  
  23.     static MySingleton*        s_pInstance;
  24. };
  25.  
  26. // in C++ file
  27. MySingleton*        MySingleton::s_pInstance = NULL;
  28.  
  29.  
In this example, it does a run-time check on the existence of a MySingleton instance.

Expand|Select|Wrap|Line Numbers
  1. class MySingleton2 {
  2.   public:
  3.     static MySingleton2& GetInstance();
  4.  
  5.   private:
  6.     MySingleton2() {
  7.         // ...
  8.     }
  9.  
  10.     ~MySingleton2() {
  11.         // ...
  12.     }
  13. };
  14.  
  15. // in C++ file
  16. MySingleton2& MySingleton2::GetInstance()
  17. {
  18.     static MySingleton2 theInstance;
  19.     return theInstance;
  20. }
  21.  
  22.  
In this example, the CTOR and DTOR are private, and the unique instance will be created on demand only, whenever GetInstance() gets called, so there is no error upon rt check.


I saw a piece of code from a website. It seems to be a simple example for a singleton class. Basically, the author creates an object in the definition of a class, which has the same name as the class. Inside the definition of the class, everything is public. One cannot instantiate another object. Is it that simple to create a singleton class? Is the all-public members in the class good enough in terms of encapsulation?

In the following is the code run successfully:

#include "stdafx.h"
#include<stdio. h>
#include <iostream>
using namespace std;

class singleton
{
public:
void print()
{
printf("hello\n ");
}
int a;
}singleton;

class client : public singleton
{};

int main()
{
// singleton s; // Can define an object before singleton
// singleton singleton;
// singleton b; #cannot define a new object after singleton
singleton.a=5;
printf("a=%d\n" ,singleton.a);
singleton.print ();

client xyz;
xyz.print();
xyz.a = 10;
cout << "xyz.a = " << xyz.a << endl;

return 0;
}
Jul 24 '07 #3
sicarie
4,677 Recognized Expert Moderator Specialist
There is another example in the C/C++ Articles section.

http://www.thescripts.com/forum/thread656124.html
Jul 24 '07 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

16
6720
by: cppaddict | last post by:
Hi, In this tutorial on singleton class in C++ (http://gethelp.devx.com/techtips/cpp_pro/10min/10min0200.asp) the author gives two implementations of a simple singleton class, claiming that only the first is safe for multi-threaded appliactions. I want to know why this so. The class is as follows:
7
3270
by: Ethan | last post by:
Hi, I have a class defined as a "Singleton" (Design Pattern). The codes are attached below. My questions are: 1. Does it has mem leak? If no, when did the destructor called? If yes, how can I avoid it? Purify does not show it has mem leak. // test if singleto class has mem leakage #include <iostream>
5
5307
by: Pelle Beckman | last post by:
Hi, I've done some progress in writing a rather simple singleton template. However, I need a smart way to pass constructor arguments via the template. I've been suggested reading "Modern C++ Design" or similar books, but I feel there are full of clever guys here who could help me out.
12
8946
by: Preets | last post by:
Can anyone explain to me the exact use of private constructors in c++ ?
6
3182
by: toton | last post by:
Hi, If I have a singleton class based on dynamic initialization (with new ) , is it considered a memory leak? Anything in C++ standard says about it ? And little off - topic question , If the singleton is initialized as a static variable , it seems there is some threading issue . Is it the issue during singleton initialization only , or during the access also? If the singleton is per thread basis (then no more singleton though ), and...
5
21154
by: Damien | last post by:
Hi all, I'm using a pretty standard C++ Singleton class, as below: template <typename T> class Singleton { public: static T* Instance() {
3
18240
weaknessforcats
by: weaknessforcats | last post by:
Design Pattern: The Singleton Overview Use the Singleton Design Pattern when you want to have only one instance of a class. This single instance must have a single global point of access. That is, regardless of where the object is hidden, everyone needs access to it. The global point of access is the object's Instance() method. Individual users need to be prevented from creating their own instances of the Singleton.
2
1581
by: Bob Johnson | last post by:
Just wondering the extent to which some of you are implementing classes as Singletons. I'm working on a brand new project and, early on, identified some obvious candidates. By "obvoius candidates" I mean classes for which terrible problems would clearly arise if more than one instance were to exist. But as I'm getting into the design of this new solution, I'm realizing that a large percentage of the classes _could be_ implemented as...
4
2821
by: John Doe | last post by:
Hi, I have a singleton class defined like this : class UIManager : public CSingleton<UIManager>, public CObject { protected: DECLARE_DYNAMIC(UIManager) friend class CSingleton<UIManager>;
0
8428
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8851
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8528
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8627
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7356
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6179
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4175
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2752
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1737
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.