Singleton class - only a single object
5 posters
Page 1 of 1
Singleton class - only a single object
make a class in c++ such that we can make only one instance of the class ( we can make only a single object )
-contributed by rohit
possible solution:
class
{
int a;
}obj1;
-contributed by rohit
possible solution:
class
{
int a;
}obj1;
ramthegreatcv- Posts : 55
Join date : 2009-01-30
Age : 36
@ramu
your solution is wrong we can create second object also by giving its name there
your solution should be such that if someone tries to declare another instance of this class then that should give an error message
your solution should be such that if someone tries to declare another instance of this class then that should give an error message
mnnit.rahul- Posts : 51
Join date : 2009-02-01
Re: Singleton class - only a single object
how about using some static counter...and checking in constructor itself?
please put the ans,if u know.
please put the ans,if u know.
@ramu
yes u are right we have to use either static variable inside class or a global variable
first try to make a object of a class which has default constructor as private and no constructor as public
first try to make a object of a class which has default constructor as private and no constructor as public
mnnit.rahul- Posts : 51
Join date : 2009-02-01
privte constructor
#include<iostream>
using namespace std;
class a
{
a(){//some code
}
a(a &);
public:
static a dube;
}
a::dube;
main()
{
cout<<"hahahha";
}
using namespace std;
class a
{
a(){//some code
}
a(a &);
public:
static a dube;
}
a::dube;
main()
{
cout<<"hahahha";
}
obama- Posts : 4
Join date : 2009-02-03
Re: Singleton class - only a single object
yes this will create a single object but the object is created inside class and cannot be used in main without scope resolution operator along with object.
there exist another solution also
waise kaun ho bhai obama bahut tagda solution tha yaar ye
there exist another solution also
waise kaun ho bhai obama bahut tagda solution tha yaar ye
mnnit.rahul- Posts : 51
Join date : 2009-02-01
I think this can also be a good solution
class sample
{
static sample *ptr ;
private:
sample( )
{
}
public:
static sample* create( )
{
if ( ptr == NULL )
ptr = new sample ;
return ptr ;
}
} ;
sample *sample::ptr = NULL ;
void main( )
{
sample *a = sample::create( ) ;
sample *b = sample::create( ) ;
}
{
static sample *ptr ;
private:
sample( )
{
}
public:
static sample* create( )
{
if ( ptr == NULL )
ptr = new sample ;
return ptr ;
}
} ;
sample *sample::ptr = NULL ;
void main( )
{
sample *a = sample::create( ) ;
sample *b = sample::create( ) ;
}
rohit vashishtha- Posts : 2
Join date : 2009-02-01
Re: Singleton class - only a single object
are rohit bhai aapka solution kabhi galat ho sakta hai
mnnit.rahul- Posts : 51
Join date : 2009-02-01
Page 1 of 1
Permissions in this forum:
You cannot reply to topics in this forum