LinuxQuestions.org
Help answer threads with 0 replies.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 01-06-2005, 01:51 AM   #1
shivaligupta
Member
 
Registered: Oct 2004
Posts: 45

Rep: Reputation: 15
C++ class-object?


In C++, How one can restrict a class so tht it can have oly one object?
 
Old 01-06-2005, 02:20 AM   #2
bm17
Member
 
Registered: Sep 2004
Location: Santa Cruz, CA, USA
Distribution: Redhat 9.0
Posts: 104

Rep: Reputation: 15
You can't, really. But you can, effectively. The question you need to ask is "What do I want to see happen when the code attempts to create a second instance?".

Still, this situation does arise often enough and is usually handled through the use of static class variables. For more information do a google search on "c++ singleton pattern".
 
Old 01-06-2005, 02:25 AM   #3
Hivemind
Member
 
Registered: Sep 2004
Posts: 273

Rep: Reputation: 30
What you want is known as a singleton and in a singleton class the constructor is private.
Instead you have a public static member function that returns a dynamically allocated instance
of the class and this instance is a static data member of the class itself.

Code:
class mysingleton
{
public:
   static mysingleton* get_instance()
   {
      if(!instance)
         instance = new mysingleton(/*arguments*/);
      return instance;
   }
private:
   mysingleton(/*arguments*/);
   static mysingleton *instance;
};

mysingleton* mysingleton::instance=NULL;
Use google to search for singleton (pattern) to learn more.
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
URGENT: ldap_add(): Add: Object class violation error 65 sierraaltae Linux - Security 1 08-05-2005 10:41 AM
Pass object variable to anothor class in JAVA hus Programming 2 05-11-2005 04:04 AM
Talk to an object in a diferent class bastl Programming 9 03-17-2005 01:36 PM
BlackBox.class & VerifierBug.class virus ??? dalek Linux - Security 4 02-29-2004 08:55 AM
Event driven object-to-object: C++ template class mecanism ( NOT STL or STDC++) bretzeltux Programming 2 12-23-2003 02:45 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 11:44 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration