freelanceprogrammers.org Forum Index » C

Re: How to create an object only once in C++?


View user's profile Post To page top
shabble Posted: Fri Jan 21, 2005 11:31 pm


Joined: 29 Dec 2004

Posts: 31
Re: How to create an object only once in C++?
From: Seran S [mailto:seranmca@...]

> How to create an object only once? When the user
>tries to create an object of that class for the second
>time, it should not allow be allowed. How to do this?
>Any idea? Please share some ideas with me.

Google for `singleton`

--
PJH

"During my service in the United States Congress, I took the initiative
in creating the Internet."
- Al Gore





Alderley plc, Arnolds Field Estate, The Downs, Wickwar, Gloucestershire, GL12
8JD, UK
Tel: +44(0)1454 294556 Fax: +44 (0)1454 299272

Website : www.alderley.com Sales : sales@... Service :
service@...

This email and its contents are confidential and are solely for the use of the
intended recipient. If you are not the original recipient you have received it
in error and any use, dissemination, forwarding, printing or copying of this
email is strictly prohibited. Should you receive this email in error please
immediately notify it@...

This email has been scanned for viruses, however you should always scan emails
with your own systems prior to opening.
Reply with quote
Send private message
View user's profile Post To page top
cppruchin Posted: Mon Jan 24, 2005 2:15 pm


Joined: 12 Jan 2005

Posts: 3
Re: How to create an object only once in C++?
Hi All,

There is a problem in this solution. If instance of this class is not
created by `new` then u can not use `delete` to destroy this object. Simply
to put in words, if u write A a, b; then while creating object b it is
illegal to call delete, and most likely an exception will be raised
complaining "Access Violation!!"

So a better solution to this problem is: Restrict the direct construction of
the object, by declaring all constructors as private, and exposing a
function say GetInstance() to return the instance of the object, like this:

class A
{
private:
A(); //Keep all constructors private
public:
static A *GetInstance()
{
static int Count;
if(Count)
{
return NULL;
}
else
{
Count++;
return new A;
}
}
};

A::A()
{
//Keep constructor code here
}

Now, to get the instance all u have to do is:

A *pa = A::GetInstance();
if(pa)
{
//Use it
}
else
{
//pa is NULL
}



With Regards,
Ruchin Kansal
HCL Technologies Ltd.
A-11 Sector-16 NOIDA, UP.
Phone: 0120-2510701/702/813. Extension: 3130



-----Original Message-----
From: manik singhal [mailto:maniksinghal@...]
Sent: Saturday, January 22, 2005 11:24 AM
To: Programmers-Town@yahoogroups.com
Subject: Re: (PT) How to create an object only once in C++?





--- Seran S <seranmca@...> wrote:

>
> Hello,
> How to create an object only once? When the
> user
> tries to create an object of that class for the
> second
> time, it should not allow be allowed. How to do
> this?
> Any idea? Please share some ideas with me.
>
> Thanks
> Seran
>
>

Hi Seran,
Try this...

class A
{
private:
static int count;
public:
A();
};

int A::count = 0;

A::A()
{
if(count ==0)
{
count ++;
}
else
{
delete *this;
}
}





> Yahoo! India Matrimony: Find your life partner
> online
> Go to: http://yahoo.shaadi.com/india-matrimony
>
>
>
>




__________________________________
Do you Yahoo!?
Yahoo! Mail - Easier than ever with enhanced search. Learn more.
http://info.mail.yahoo.com/mail_250





To unsubscribe : programmers-town-unsubscribe@yahoogroups.com


Yahoo! Groups Links
Reply with quote
Send private message
View user's profile Post To page top
cppruchin Posted: Mon Jan 24, 2005 2:23 pm


Joined: 12 Jan 2005

Posts: 3
Re: How to create an object only once in C++?
Exactly, but point is "How to discard?"

With Regards,
Ruchin Kansal
HCL Technologies Ltd.
A-11 Sector-16 NOIDA, UP.
Phone: 0120-2510701/702/813. Extension: 3130



-----Original Message-----
From: parminder dhesi [mailto:dhesi_nangal@...]
Sent: Sunday, January 23, 2005 3:23 PM
To: Programmers-Town@yahoogroups.com
Subject: Re: (PT) How to create an object only once in C++?




hi,
Simple , just include one static variable say
countObject as STATIC variable eg
static int countObject = 0; in ur class whose objects
u r creating then in constructor check the value of
countObject . it should no be greater than one if yes
discard the creation of new Object.

bye


________________________________________________________________________
Yahoo! India Matrimony: Find your life partner online
Go to: http://yahoo.shaadi.com/india-matrimony





To unsubscribe : programmers-town-unsubscribe@yahoogroups.com


Yahoo! Groups Links
Reply with quote
Send private message
View user's profile Post To page top
roohani15 Posted: Mon Jan 24, 2005 3:37 pm


Joined: 25 Jan 2005

Posts: 8
Re: How to create an object only once in C++?
i think this might help u
 
In some cases an object is needed only temporarily. Explicitly introducing a variable to name this temporary object can be avoided by creating an anonymous object. An anonymous object is an object in every sense except that it has no name. Consider the following example: Location initialLocation(100, 100), displayLocation(200,200);
Shape initialShape(150, 200), displayShape(300, 200);
Frame window (initialLocation, initialShape);
Frame display (displayLocation, displayShape);
...
Location newLocation(300,300);
Location newShape (150,150);
window.MoveTo(newLocation);
display.Resize(newShape);
window.MoveTo( Location(300,300) );
display.Resize( Shape(150,150) );
In the construction of the window object two anonymous objects are created, one anonymous Location object and one anonymous Shape object. The display object is also created using two anonymous objects. Finally, the MoveTo and Resize operations also use anonymous objects. It is important to realize that the example with named objects and the one with anonymous objects have exactly the same observable effects.   

 
Assume that all of the Location and Shape objects have no other uses than the ones shown in the example. Using explicitly declared and named objects that are used only once has several disadvantages. First, the programmer has to write a separate declaration and invent a meaningful name for an object that plays a very minor (perhaps trivial role). This effort may not be seen as worthwhile. Second, the object may continue to exist for some time after it has been used even though it is not needed. In the above example, the scope of "initialLocation" and "window" are the same. However, the window object may be needed far longer than the Location object though both objects will continue to exist. It is more efficient use of memory to be able to delete the Location object as soon as it useful lifetime has ended. Third, the reader of the code is not given a clear indication that objects such as "initialLocation" and "displayLocation" are, in fact, used in such a localized way. Only by reading all of the code in this scope can it be determined whether those objects are used only once or used
again later. Anonymous objects are a more efficient and clearer way to create and use an object that is intended only to be used in a single (localized) place. These objects are called "anonymous" objects because they are not given a name. Instead the object is declared directly in the place where it is needed. The example above can be re-written using anonymous objects as follows:
Frame window ( Location(100,100), Shape(150, 200) );
Frame display ( Location(200,200), Shape(300, 200) );

 
 
 
 
 
 
 
 
"Ruchin Kansal, Noida" <ruchink@...> wrote:
Hi All,There is a problem in this solution. If instance of this class is notcreated by `new` then u can not use `delete` to destroy this object. Simplyto put in words, if u write A a, b; then while creating object b it isillegal to call delete, and most likely an exception will be raisedcomplaining "Access Violation!!"So a better solution to this problem is: Restrict the direct construction ofthe object, by declaring all constructors as private, and exposing afunction say GetInstance() to return the instance of the object, like this:class A{private:A(); //Keep all constructors privatepublic:static A *GetInstance(){      static int Count;      if(Count)      {     
      return NULL;      }      else      {            Count++;            return new A;      }}};A::A(){      //Keep constructor code here}Now, to get the instance all u have to do is:A *pa = A::GetInstance();if(pa){      //Use it}else{      //pa is NULL}With Regards,Ruchin KansalHCL Technologies Ltd.A-11 Sector-16 NOIDA, UP.Phone: 0120-2510701/702/813. Extension: 3130-----Original Message-----From: manik singhal [mailto:maniksinghal@...]Sent: Saturday, January 22, 2005 11:24 AMTo: Programmers-Town@yahoogroups.comSubject:
Re: (PT) How to create an object only once in C++?--- Seran S <seranmca@...> wrote:> > Hello,>      How to create an object only once? When the> user> tries to create an object of that class for the> second> time, it should not allow be allowed. How to do> this?> Any idea? Please share some ideas with me.> > Thanks> Seran> > Hi Seran, Try this...class A{private:static int count;public:A();};int A::count = 0;A::A(){if(count ==0){  count ++;}else{   delete *this;}}> Yahoo! India Matrimony: Find your life partner> online> Go to: http://yahoo.shaadi.com/india-matrimony> > > >
            __________________________________ Do you Yahoo!? Yahoo! Mail - Easier than ever with enhanced search. Learn more.http://info.mail.yahoo.com/mail_250To unsubscribe : programmers-town-unsubscribe@yahoogroups.comYahoo! Groups LinksTo unsubscribe : programmers-town-unsubscribe@yahoogroups.com
Do you Yahoo!? Yahoo! Search presents - Jib Jab`s `Second Term`
Reply with quote
Send private message
View user's profile Post To page top
pankaj.munjal@... Posted: Mon Jan 24, 2005 4:34 pm


Joined: 24 Jan 2005

Posts: 1
Re: How to create an object only once in C++?
You can use the concept of Singleton Classes.
The following code implements a singleton class:

class Singleton {
int i;
void operator=(Singleton&);
Singleton(const Singleton&);
public:
static Singleton s;
Singleton(int x) : i(x) { }
static Singleton& getHandle() {
return s;
}
int getValue() { return i; }
void setValue(int x) { i = x; }
};

int main() {
Singleton& s = Singleton::getHandle();
cout << s.getValue() << endl;
Singleton& s2 = Singleton::getHandle();
s2.setValue(9);
cout << s.getValue() << endl;
}

Cheers,
Pankaj.


-----Original Message-----
From: parminder dhesi [mailto:dhesi_nangal@...]
Sent: Sunday, January 23, 2005 3:23 PM
To: Programmers-Town@yahoogroups.com
Subject: Re: (PT) How to create an object only once in C++?



hi,
Simple , just include one static variable say countObject as STATIC
variable eg static int countObject = 0; in ur class whose objects u r
creating then in constructor check the value of countObject . it should
no be greater than one if yes discard the creation of new Object.

bye


________________________________________________________________________
Yahoo! India Matrimony: Find your life partner online Go to:
http://yahoo.shaadi.com/india-matrimony





To unsubscribe : programmers-town-unsubscribe@yahoogroups.com


Yahoo! Groups Links
Reply with quote
Send private message
View user's profile Post To page top
anand_at_maiet Posted: Mon Jan 24, 2005 6:45 pm


Joined: 24 Jan 2005

Posts: 1
Re: How to create an object only once in C++?
I think using following steps we can discard......
1. overload the default constructor
2.design your own default constructor which thows an exception.
3. throw an exception when the static count is out of limit say 1. 
"Ruchin Kansal, Noida" <ruchink@...> wrote:
Exactly, but point is "How to discard?"With Regards,Ruchin KansalHCL Technologies Ltd.A-11 Sector-16 NOIDA, UP.Phone: 0120-2510701/702/813. Extension: 3130-----Original Message-----From: parminder dhesi [mailto:dhesi_nangal@...]Sent: Sunday, January 23, 2005 3:23 PMTo: Programmers-Town@yahoogroups.comSubject: Re: (PT) How to create an object only once in C++?hi,Simple , just include one static variable saycountObject as STATIC variable eg static int countObject = 0; in ur class whose objectsu r creating then in constructor check the value ofcountObject . it should no be greater than one if yesdiscard the creation of new Object.bye________________________________________________________________________Yahoo! India Matrimony: Find your life partner
onlineGo to: http://yahoo.shaadi.com/india-matrimonyTo unsubscribe : programmers-town-unsubscribe@yahoogroups.comYahoo! Groups LinksTo unsubscribe : programmers-town-unsubscribe@yahoogroups.com

Yahoo! India Matrimony: Find your life partner
online.
Reply with quote
Send private message
View user's profile Post To page top
mandarpb Posted: Mon Jan 24, 2005 6:54 pm


Joined: 24 Jan 2005

Posts: 1
Re: How to create an object only once in C++?
You need a static poiter, which should store this*. In
the constructor, check if this is null, create
instance else return this pointer.
Check singleton design pattern for this.

Regards,
Mandar

--- "Ruchin Kansal, Noida" <ruchink@...>
wrote:

>
> Exactly, but point is "How to discard?"
>
> With Regards,
> Ruchin Kansal
> HCL Technologies Ltd.
> A-11 Sector-16 NOIDA, UP.
> Phone: 0120-2510701/702/813. Extension: 3130
>
>
>
> -----Original Message-----
> From: parminder dhesi
> [mailto:dhesi_nangal@...]
> Sent: Sunday, January 23, 2005 3:23 PM
> To: Programmers-Town@yahoogroups.com
> Subject: Re: (PT) How to create an object only once
> in C++?
>
>
>
>
> hi,
> Simple , just include one static variable say
> countObject as STATIC variable eg
> static int countObject = 0; in ur class whose
> objects
> u r creating then in constructor check the value of
> countObject . it should no be greater than one if
> yes
> discard the creation of new Object.
>
> bye
>
>
>
________________________________________________________________________
> Yahoo! India Matrimony: Find your life partner
> online
> Go to: http://yahoo.shaadi.com/india-matrimony
>
>
>
>
>
> To unsubscribe :
> programmers-town-unsubscribe@yahoogroups.com
>
>
> Yahoo! Groups Links
>
>
>
>
>
>
>
>
>
>




__________________________________
Do you Yahoo!?
Yahoo! Mail - now with 250MB free storage. Learn more.
http://info.mail.yahoo.com/mail_250
Reply with quote
Send private message
View user's profile Post To page top
vvsarun Posted: Mon Jan 24, 2005 8:49 pm


Joined: 24 Jan 2005

Posts: 1
Re: How to create an object only once in C++?
by declaring constructor in a private mode and
returning the object by calling a static member
function which is declared in public mode.

otherwise by creating a singleton class.

go through desing patterns - singleton class



__________________________________
Do you Yahoo!?
Take Yahoo! Mail with you! Get it on your mobile phone.
http://mobile.yahoo.com/maildemo
Reply with quote
Send private message
View user's profile Post To page top
cool_alok Posted: Fri Jan 28, 2005 12:00 pm


Joined: 05 Feb 2005

Posts: 5
Re: How to create an object only once in C++?
 
Hello Group Member,
 
  i like to discuss Solution of SingleTon Source Given By Ms roohani chopra
 
eg: of singleton clas
class singleton
{
 singleton();      // make it private
public:
 singleton * getInstance();
 static singleton* classObj = 0;
};
 
singleton *singleton ::getInstance()
{
 if(classObj == NULL)
   {
     classObj  = new singleton ;
   }
 return classObj  ;

 
main()
{
   singleton *obj = NULL;
   obj  = obj->getInstance();
 
}
 
 
After Compiling it i am getting these two Linker error
1.obj : error LNK2001: unresolved external symbol "private: __thiscall singleton::singleton(void)" (??0singleton@@AAE@XZ)1.obj : error LNK2001: unresolved external symbol "public: static class singleton * singleton::classObj" (?classObj@singleton@@2PAV1@A)Debug/SingleTon.exe : fatal error LNK1120: 2 unresolved externals
so i Request Ms Roohani to come forward and give some live Example.
 
Thanks
With RegardsAlok GuptaVisit me at http://alok.bizhat.com
 
                           "I think this will Help"
 
 
 
Reply with quote
Send private message
View user's profile Post To page top
raju_chess_id Posted: Sat Jan 29, 2005 3:58 pm


Joined: 29 Jan 2005

Posts: 2
Re: How to create an object only once in C++?
--- alok <alok@...> wrote:

>
> Hello Group Member,
>
> i like to discuss Solution of SingleTon Source
> Given By Ms roohani chopra
>
> eg: of singleton clas
> class singleton
> {
> singleton(); // make it private
> public:
> singleton * getInstance();
> static singleton* classObj = 0;
> };
>
> singleton *singleton ::getInstance()
> {
> if(classObj == NULL)
> {
> classObj = new singleton ;
> }
> return classObj ;
> }
>
> main()
> {
> singleton *obj = NULL;
> obj = obj->getInstance();
>
> }
>
>
> After Compiling it i am getting these two Linker
> error
> 1.obj : error LNK2001: unresolved external symbol
> "private: __thiscall singleton::singleton(void)"
> (??0singleton@@AAE@XZ)
> 1.obj : error LNK2001: unresolved external symbol
> "public: static class singleton *
> singleton::classObj" (?classObj@singleton@@2PAV1@A)
> Debug/SingleTon.exe : fatal error LNK1120: 2
> unresolved externals
>
> so i Request Ms Roohani to come forward and give
> some live Example.
>
> Thanks
>
> With Regards
> Alok Gupta
> Visit me at http://alok.bizhat.com
>
> "I think this will Help"
>
>
>


Hi ,


I think this link will give you different approaches
for you singleton class problem
"http://www.codeguru.com/Cpp/Cpp/cpp_mfc/singletons/article.php/c823/"

Thanks




__________________________________
Do you Yahoo!?
Take Yahoo! Mail with you! Get it on your mobile phone.
http://mobile.yahoo.com/maildemo
Reply with quote
Send private message
View user's profile Post To page top
mailfrmgroups Posted: Sun Jan 30, 2005 6:32 pm


Joined: 04 Feb 2005

Posts: 2
Re: How to create an object only once in C++?
Hi,
 
The error here is in class declaration.
Change the class declaration as follows:
 

class singleton
{
private:
      static singleton* classObj;
      singleton();     
public:
      static singleton * getInstance();
};
 
singleton * singleton::classObj = 0;
 
Well thats it....
 
Regards,
Kiran.alok <alok@...> wrote:

 
Hello Group Member,
 
  i like to discuss Solution of SingleTon Source Given By Ms roohani chopra
 
eg: of singleton clas
class singleton
{
 singleton();      // make it private
public:
 singleton * getInstance();
 static singleton* classObj = 0;
};
 
singleton *singleton ::getInstance()
{
 if(classObj == NULL)
   {
     classObj  = new singleton ;
   }
 return classObj  ;

 
main()
{
   singleton *obj = NULL;
   obj  = obj->getInstance();
 
}
 
 
After Compiling it i am getting these two Linker error
1.obj : error LNK2001: unresolved external symbol "private: __thiscall singleton::singleton(void)" (??0singleton@@AAE@XZ)1.obj : error LNK2001: unresolved external symbol "public: static class singleton * singleton::classObj" (?classObj@singleton@@2PAV1@A)Debug/SingleTon.exe : fatal error LNK1120: 2 unresolved externals
so i Request Ms Roohani to come forward and give some live Example.
 
Thanks
With RegardsAlok GuptaVisit me at http://alok.bizhat.com
 
                           "I think this will Help"
 
 
 To unsubscribe : programmers-town-unsubscribe@yahoogroups.com
Do you Yahoo!? Yahoo! Search presents - Jib Jab`s `Second Term`
Reply with quote
Send private message
View user's profile Post To page top
jaggi_manish Posted: Mon Jan 31, 2005 12:04 pm


Joined: 31 Jan 2005

Posts: 1
Re: How to create an object only once in C++?
A snippet from msdn

// This program illustrates how to write a singleton class (a class that
// can have only one instance) in C++. The trick is to make the default
// constructor, copy constructor and assignment operator all private. A
// static function GetInstance returns the one and only object instance.
//
// If you attempt to compile this program, it will generate errors.
// (See main function below.)
//
class CSingleton {
public:
static CSingleton& GetInstance() {
static CSingleton theInstance; // one and only instance
return theInstance;
}

protected:
// need default ctor for GetInstance.
// ctor is protected, not private in case you want to derive.
CSingleton() { }

private:
CSingleton(const CSingleton& o) { }
CSingleton& operator=(const CSingleton& o) { }
};

main()
{
// These lines will not compile:
CSingleton x = CSingleton::GetInstance(); // error: private
// copy ctor!
CSingleton y = CSingleton::GetInstance(); // error: private
// copy ctor!
x = y; // error: private
// assignment!
}


On Fri, 28 Jan 2005 11:30:05 +0530, alok <alok@...> wrote:
>
>
> Hello Group Member,
>
> i like to discuss Solution of SingleTon Source Given By Ms roohani chopra
>
> eg: of singleton clas
> class singleton
> {
> singleton(); // make it private
> public:
> singleton * getInstance();
> static singleton* classObj = 0;
> };
>
> singleton *singleton ::getInstance()
> {
> if(classObj == NULL)
> {
> classObj = new singleton ;
> }
> return classObj ;
> }
>
> main()
> {
> singleton *obj = NULL;
> obj = obj->getInstance();
>
> }
>
>
> After Compiling it i am getting these two Linker error
> 1.obj : error LNK2001: unresolved external symbol "private: __thiscall
> singleton::singleton(void)" (??0singleton@@AAE@XZ)
> 1.obj : error LNK2001: unresolved external symbol "public: static class
> singleton * singleton::classObj" (?classObj@singleton@@2PAV1@A)
> Debug/SingleTon.exe : fatal error LNK1120: 2 unresolved externals
>
> so i Request Ms Roohani to come forward and give some live Example.
>
> Thanks
>
> With Regards
> Alok Gupta
> Visit me at http://alok.bizhat.com
>
> "I think this will Help"
>
>
>
>
>
> To unsubscribe : programmers-town-unsubscribe@yahoogroups.com
>
>
>
>
> ________________________________
> Yahoo! Groups Links
>
> To visit your group on the web, go to:
> http://groups.yahoo.com/group/Programmers-Town/
>
> To unsubscribe from this group, send an email to:
> Programmers-Town-unsubscribe@yahoogroups.com
>
> Your use of Yahoo! Groups is subject to the Yahoo! Terms of Service.


--
Manish Jaggi
Reply with quote
Send private message
View user's profile Post To page top
cool_alok Posted: Sat Feb 05, 2005 5:12 pm


Joined: 05 Feb 2005

Posts: 5
Re: How to create an object only once in C++?
THanks Raju for replying to my problem and also i am thank ful to other people who help me to clear my doubt
With RegardsAlok GuptaVisit me at http://alok.bizhat.com
 
                           "I think this will Help"

----- Original Message -----
From: Raju Sholivedu
To: Programmers-Town@yahoogroups.com
Sent: Saturday, January 29, 2005 3:28 PM
Subject: Re: (PT) How to create an object only once in C++?
--- alok <alok@...> wrote:> > Hello Group Member,> >   i like to discuss Solution of SingleTon Source> Given By Ms roohani chopra > > eg: of singleton clas > class singleton> {>  singleton();      // make it private > public:>  singleton * getInstance();>  static singleton* classObj = 0;> };> > singleton *singleton ::getInstance()> {>  if(classObj == NULL)>    {>      classObj  = new singleton ;>    }>  return classObj  ;> } > > main()> {>    singleton *obj = NULL;>    obj  = obj->getInstance();> > }> > > After Compiling it i am getting these two Linker> error> 1.obj : error LNK2001: unresolved external symbol> "private: __thiscall singleton::singleton(void)"> (??0singleton@@AAE@XZ)> 1.obj : error LNK2001: unresolved external symbol> "public: static class singleton *> singleton::classObj" (?classObj@singleton@@2PAV1@A)> Debug/SingleTon.exe : fatal error LNK1120: 2> unresolved externals> > so i Request Ms Roohani to come forward and give> some live Example.> > Thanks> > With Regards> Alok Gupta> Visit me at http://alok.bizhat.com> >                            "I think this will Help"> > > Hi ,I think this link will give you different approachesfor you singleton class problem"http://www.codeguru.com/Cpp/Cpp/cpp_mfc/singletons/article.php/c823/"Thanks            __________________________________ Do you Yahoo!? Take Yahoo! Mail with you! Get it on your mobile phone. http://mobile.yahoo.com/maildemo To unsubscribe : programmers-town-unsubscribe@yahoogroups.com
Reply with quote
Send private message
Post new topic Reply to topic
Display posts from previous:   
 

All times are GMT
Page 1 of 1
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
Freelace Website Designer - Customer web design and software building.
English Courses in England - reservation calendar script
Land Surveying -Stonex instruments and equipments
China Wholesale - Electronics Products
Character Studio - Tutorials and Help