472,353 Members | 1,020 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 472,353 developers and data experts.

Singleton class - by overloading "new" operator

ishwarDhumal
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>
  4.  
  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.     }
  13.  
  14.  void *operator new(size_t);    //overload new operator for class which is to be made iSingleton.
  15. };
  16.  
  17.  iSingleton *iSingleton::sptr=NULL;    //initialize pointer to NULL
  18.  
  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. }
  26.  
  27. int main()
  28. {
  29.  clrscr();
  30.  iSingleton *sptr1=new iSingleton;      //first object created
  31.  iSingleton *sptr2=new iSingleton;      //second object created
  32.  
  33.  if(sptr1==sptr2)
  34.       cout<<"\nGiven class is a Singleton class.";
  35.  else
  36.       cout<<"\nGiven class is not a Singleton class.";
  37.  
  38.  getch();
  39.  return 0;
  40. }
  41.  
Attached Files
File Type: txt iSingleton.txt (1.0 KB, 593 views)
Aug 8 '12 #1
7 37777
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
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
gr8, very interesting and useful. this code is very optimize for singleton design pattern.
Aug 14 '12 #4
weaknessforcats
9,208 Expert Mod 8TB
Did anyone read: http://bytes.com/topic/c/insights/65...erns-singleton?
Jan 8 '13 #5
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
weaknessforcats
9,208 Expert Mod 8TB
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
Thanks SumitDhyani for your reply.
Jun 23 '14 #8

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

Similar topics

2
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...
0
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
18
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...
5
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...
1
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...
3
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
5
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...
14
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...
36
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...
12
by: Robert Fuchs | last post by:
Hello, This example: public class BaseC { public int x; public void Invoke() {} } public class DerivedC : BaseC
1
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and...
0
by: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge...
0
by: antdb | last post by:
Ⅰ. Advantage of AntDB: hyper-convergence + streaming processing engine In the overall architecture, a new "hyper-convergence" concept was...
0
by: Matthew3360 | last post by:
Hi there. I have been struggling to find out how to use a variable as my location in my header redirect function. Here is my code. ...
2
by: Matthew3360 | last post by:
Hi, I have a python app that i want to be able to get variables from a php page on my webserver. My python app is on my computer. How would I make it...
0
hi
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific...
0
by: Matthew3360 | last post by:
Hi, I have been trying to connect to a local host using php curl. But I am finding it hard to do this. I am doing the curl get request from my web...
0
Oralloy
by: Oralloy | last post by:
Hello Folks, I am trying to hook up a CPU which I designed using SystemC to I/O pins on an FPGA. My problem (spelled failure) is with the...
0
by: Carina712 | last post by:
Setting background colors for Excel documents can help to improve the visual appeal of the document and make it easier to read and understand....

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.