Question about singleton

J

Jack

If class A is a singleton, class B inherits class A,

class B : public class A

Is class B also a singleton?

Thanks.

Jack
 
K

Kai-Uwe Bux

Jack said:
If class A is a singleton, class B inherits class A,

class B : public class A

Is class B also a singleton?

Well, if class A is a singleton, it will ensure that only one instance is
created. Since creation of a B instance requires creation of an A instance,
you can only create one. In that sense, class B is a singleton.

However, if I recall correctly, there was a little more to a singleton:
something about a uniform point of access. It is not clear at all, whether
and how class B could inherit that part. In order to support that, class A
would need to be designed appropriately.


Best

Kai-Uwe Bux
 
G

Guest

If class A is a singleton, class B inherits class A,

class B : public class A

Is class B also a singleton?

Usually a singleton have a private constructor, which means that you can
not create an A instance when creating the B instance, in other words
you can not inherit from a singleton.
 
U

Uday Bidkar

If class A is a singleton, class B inherits class A,

class B : public class A

Is class B also a singleton?

Thanks.

Jack

It depends on how singleton pattern is implemented in class A. I guess
if the constructor of A is made private, then you wont be able to
initialize even a single object of B and if its protected, you can
implement B as singleton and non-singleton as well as you would be
able to call A's constructo from that of B.
 
J

Jack

It depends on how singleton pattern is implemented in class A. I guess
if the constructor of A is made private, then you wont be able to
initialize even a single object of B and if its protected, you can
implement B as singleton and non-singleton as well as you would be
able to call A's constructo from that of B.

How about this implementation:

class A{

public:
virtual A* getinstance()
{
if(ptr_A == NULL)
ptr_A = new A;
return ptr_A;
}

protected:
A():ptr_A(NULL){}

private:
A* ptr_A;
};

class B : public class A
{
public:
A* getinstance()
{
if(ptr_B == NULL)
ptr_B = new B;
return ptr_B;
}

protected:
B(): ptr_B(NULL),A(NULL){}

private:
B* ptr_B;
};

Thanks.

Jack
 
U

Uday Bidkar

Could you please elaborate on what exactly you want to figure out in
post above?
 
G

Gary Coulbourne

You're probably better off if you can refactor the class so that the
singleton nature can be handled with dependency injection, rather than
making it an explicit singleton.

Peace,
Gary
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,521
Members
44,995
Latest member
PinupduzSap

Latest Threads

Top