C
cppaddict
Hi,
I am writing a program and needs to know one of its object members
before it can be initialized. It doesn't really matter for my
question (which a C++ question, not a windows question), but the class
is used in a windows program and has an HWND member ( a handle to a
window), and to make an sense the class must know what the member is.
But this puts me in the position of having no default constructor, and
I've heard that is considered bad form. What is the right way to
handle this situation? Or is it okay to have a class which has no
default constructor?
I found one other thread on this subject in the archives, but I didn't
understand the solution proposed, which involved using the Factory
Design. I don't quite see how this solves the problem, and would love
an explanation of that, if it's relevant. (code is below)
Thanks for any help,
cpp
------BEGIN SNIPPET-----
class A {
private:
A() : x_(sX) {};
static B& sX;
public:
static A* makeArrayOfA(const B&x, const long numA) { sX = x; return
new
A[numA];};
....
};
---------END SNIPPET----------
I am writing a program and needs to know one of its object members
before it can be initialized. It doesn't really matter for my
question (which a C++ question, not a windows question), but the class
is used in a windows program and has an HWND member ( a handle to a
window), and to make an sense the class must know what the member is.
But this puts me in the position of having no default constructor, and
I've heard that is considered bad form. What is the right way to
handle this situation? Or is it okay to have a class which has no
default constructor?
I found one other thread on this subject in the archives, but I didn't
understand the solution proposed, which involved using the Factory
Design. I don't quite see how this solves the problem, and would love
an explanation of that, if it's relevant. (code is below)
Thanks for any help,
cpp
------BEGIN SNIPPET-----
How about a factory?I have come across many instances where it seems like a class
is most correctly encapsulated when there is NO default constructor.
E.g., I might end up with something like:
class A {
private:
const B& x_;
public:
A(const B& x) : x_(x) {}
// other stuff
};
In this example, I have to initialize x_ to something meaningful when
the class is constructed. More importantly, I want the constructor
to leave A in a valid state, where A is valid only if x_ is meaningfully
initialized (to something only the caller can determine).
class A {
private:
A() : x_(sX) {};
static B& sX;
public:
static A* makeArrayOfA(const B&x, const long numA) { sX = x; return
new
A[numA];};
....
};
---------END SNIPPET----------