473,836 Members | 2,292 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Singleton class - by overloading "new" operator

6 New Member
Singleton class - is a class of which only one object exists in memory at a time.
We can create singleton class using :
  • A static method or
  • By overloading "new" operator for that class.
Here is a simple example of creating singleton class by overloading "new" operator for that class.

Expand|Select|Wrap|Line Numbers
  1. #include<iostream.h>
  2. #include<conio.h>
  3. #include<alloc.h>
  5. class iSingleton
  6. {
  7.  static iSingleton *sptr;    //this pointer points to object of the class
  8.  public:
  9.     iSingleton()    //public constructor
  10.     {
  11.        sptr=this;
  12.     }
  14.  void *operator new(size_t);    //overload new operator for class which is to be made iSingleton.
  15. };
  17.  iSingleton *iSingleton::sptr=NULL;    //initialize pointer to NULL
  19. void *iSingleton::operator new(size_t s)
  20. {
  21.   if(sptr!=NULL)    //if already one object is created return reference to same object
  22.      return sptr;
  23.   else
  24.      return malloc(s);    //else allocate memory for one (first) object
  25. }
  27. int main()
  28. {
  29.  clrscr();
  30.  iSingleton *sptr1=new iSingleton;      //first object created
  31.  iSingleton *sptr2=new iSingleton;      //second object created
  33.  if(sptr1==sptr2)
  34.       cout<<"\nGiven class is a Singleton class.";
  35.  else
  36.       cout<<"\nGiven class is not a Singleton class.";
  38.  getch();
  39.  return 0;
  40. }
Attached Files
File Type: txt iSingleton.txt (1.0 KB, 645 views)
Aug 8 '12 #1
7 38068
93 New Member
Wow, very interesting and useful. I'm currently working on my first videogame (it's a for fun project) and was wrapping my head around how could I use the least amount of memory when creating objects like floor blocks in a 2D game. This information could prove useful. Say, if I have a block on the screen that is a singleton class in memory, does that mean that if I want its texture in multiple locations on the screen I cant simply change the rectangle in the class because it is only one object in memory? In other words, can I replicate the texture without creating copies of the the class? I'm thinking of a platform type of game. Also, what situations are singleton classes most often used in the professional world?
Aug 9 '12 #2
6 New Member
I think Singleton class is useful in situation where only one instance of the class is to be reused throughout the application.
  • It provides global access to the single instance of the class and
  • It guarantees that no more than one instance of that type can ever be created.
I don't know about 2D game programming so can't say about it..
Aug 10 '12 #3
4 New Member
gr8, very interesting and useful. this code is very optimize for singleton design pattern.
Aug 14 '12 #4
9,208 Recognized Expert Moderator Expert
Did anyone read: http://bytes.com/topic/c/insights/65...erns-singleton?
Jan 8 '13 #5
1 New Member
Nice thought, just a suggestion:
It works fine till the objects are created on heap using operator new.

Since the default constructor is still public, multiple number of stack objects can be created by writing:
iSingleton ob1;
iSingleton ob2;//.. and so on

What you can do to avoid this is to declare the destructor private. That way the code won't even compile if someone dares to declare automatic( or even static ) objects( since declaring an automatic objects implicitly means calling the destructor at some later point).

The only way left to create objects then will be to use operator new.
Jun 23 '14 #6
9,208 Recognized Expert Moderator Expert
It's not that there is one singleton object. You cannot prevent someone creating an object either on the stack or the heap.

The key is that there is a universal point of access where only one object is referenced. That is the singleton object.

To find the correct object, you use the Instance() method of the object. So if you have 25 objects of the Singleton class you will find that the Instance() method of these objects always returns the same address. That address is the official singleton.
Jun 23 '14 #7
6 New Member
Thanks SumitDhyani for your reply.
Jun 23 '14 #8

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

Similar topics

by: Vijayaraghavan Kalyanapasupathy | last post by:
Hello All, I just learnt about smart pointers. Given the advantages of using smart-pointers, as a designer of say a List object, I can inhibit creation of the actual objects by making its constructors and then making the smart pointer a friend of the class (I am talking about a specific smart pointer implementation for a specific object). Now, it seems to me that inhibiting the use of "new" with the smart pointer would enhance things....
by: Tim Milstead | last post by:
(CODE AT END OF POST) I have got some code for finding memory leaks that works well with: new() and needs to be extended to work with new
by: Leslaw Bieniasz | last post by:
Cracow, 28.10.2004 Hello, I have a program that intensively allocates and deletes lots of relatively small objects, using "new" operator. The objects themselves are composed of smaller objects, again allocated using "new". From my tests I deduce that a considerable part of the computational time is spent on the memory allocation, which makes the program substantially slower compared to the equivalent code written using
by: Mark P | last post by:
I think my previous posts on this subject are too verbose and are scaring off replies so I'll keep this one brief: If I define my own operator new(size_t size) in a class, does that automatically hide (global) placement new? Would this prevent STL container classes from working (e.g., does std::allocator require placement new for its construct() method?)? Thanks for your help,
by: sven_c_t | last post by:
Hi! Probably a newbie question. I´ve been working a bit with the widget toolkit FLTK and I have been wondering why there is such a heavy use of the new operator, when it does not seem to be nessesary (at least to me). What follows is an example taken from the FLTK tutorial: ------------- #include <FL/Fl.H> #include <FL/Fl_Window.H>
by: JL | last post by:
Hi all, I like to know that how to check the class variable is "New"(to object) or not? Thanks a lot
by: Sam | last post by:
Hi everyone Could anyone help me understand the usage of the "New" keyword I'm new to VB.Net. 1. Why do we use the "New" keyword on some object type variables such as the myPen of the example below and not with the bgColor. Both the Pen and Color are objects Dim myPen As Pen = New Pen(Color.AquaMarine)
by: mlw | last post by:
Do not take anything about this, it is not a flame or troll, while I'm not new to Java I favor C++. However, I may need to use it in a contract position, and am concerned that the restrictions it places on application code. Take, for instance, this C++ construct: class foo { char *m_name;
by: Pat | last post by:
Hi, I've run into a strange problem, but one that seems like it might be fairly common. I have a single base class, from which several other classes are derived. To keep the example simple, the base class is "Animal" and the derived classes are "Cat," "Dog," and "Horse." The base class has a pure virtual method:
by: Robert Fuchs | last post by:
Hello, This example: public class BaseC { public int x; public void Invoke() {} } public class DerivedC : BaseC
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...
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...
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,...
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...
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...
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
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...
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
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.