W
W Karas
Suppose you have a class that has only one instance, and there is
little reason to think it would ever make sense for the class to have
more than one instance. What are some criteria for deciding whether
it should even be a class? For example, does:
class A
{
private:
int a;
public:
void x();
void y();
};
A only_instance_of_a;
or
class A
{
private:
static int a;
public:
static void x();
static void y();
};
have major advantages over:
// Header file
namespace A
{
void x();
void y();
}
-------
// Implementation file.
namespace A
{
namespace Impl
{
int a;
}
using namespace Impl;
void x() { ... }
void y() { ... }
}
The one obvious advantage of a class is that privacy is strictly
enforced by the compiler (as opposed to putting private stuff in a sub-
namespace that is private by convention). The disadvantage of a class
is the classic problem of trying to minimize implementation details in
the header file for external code. I'm aware of the technique of
using a pointer or reference to class private data, but is it more
trouble than it's worth? It seem generally unintuitive to have a
class of objects with only one object in it.
little reason to think it would ever make sense for the class to have
more than one instance. What are some criteria for deciding whether
it should even be a class? For example, does:
class A
{
private:
int a;
public:
void x();
void y();
};
A only_instance_of_a;
or
class A
{
private:
static int a;
public:
static void x();
static void y();
};
have major advantages over:
// Header file
namespace A
{
void x();
void y();
}
-------
// Implementation file.
namespace A
{
namespace Impl
{
int a;
}
using namespace Impl;
void x() { ... }
void y() { ... }
}
The one obvious advantage of a class is that privacy is strictly
enforced by the compiler (as opposed to putting private stuff in a sub-
namespace that is private by convention). The disadvantage of a class
is the classic problem of trying to minimize implementation details in
the header file for external code. I'm aware of the technique of
using a pointer or reference to class private data, but is it more
trouble than it's worth? It seem generally unintuitive to have a
class of objects with only one object in it.