R
[rob desbois]
Hi,
I want a class whose invariant is that the contained data members are
valid - the constructor establishes this invariant, methods assume it
as their precondition and maintain it as their postcondition.
This requires the class to NOT have a default constructor.
I need to store instances of this class in STL containers, which
unfortunately requires that the class has a default constructor. The
obvious solution here is that I have to implement a default
constructor which leaves the class in an invalid state, although this
unfortunately means that every method now has to check the invariant
as a precondition to ensure that it's not vulnerable to class users
who might use the default constructor and not read the documentation.
Another requirement is that I need to implement (non-member) I/O
streaming functions. The output operator<<() is no problem, but again
with an input operator:
istream& operator>>(istream& in, const Foo& f);
I have to use this like so:
Foo f;
in >> f;
This obviously requires, again, that I can construct an instance
through the default constructor thus generating an invalid object.
Is there some great guideline for designing that everyone else knows
and I don't? Is this one of those 'pain-in-the-backside' things that
we just have to put up with and end up implementing default
constructors and invariant checks just so we can do the other things
we need to do?
Thanks for any help anyone can offer...
--rob
I want a class whose invariant is that the contained data members are
valid - the constructor establishes this invariant, methods assume it
as their precondition and maintain it as their postcondition.
This requires the class to NOT have a default constructor.
I need to store instances of this class in STL containers, which
unfortunately requires that the class has a default constructor. The
obvious solution here is that I have to implement a default
constructor which leaves the class in an invalid state, although this
unfortunately means that every method now has to check the invariant
as a precondition to ensure that it's not vulnerable to class users
who might use the default constructor and not read the documentation.
Another requirement is that I need to implement (non-member) I/O
streaming functions. The output operator<<() is no problem, but again
with an input operator:
istream& operator>>(istream& in, const Foo& f);
I have to use this like so:
Foo f;
in >> f;
This obviously requires, again, that I can construct an instance
through the default constructor thus generating an invalid object.
Is there some great guideline for designing that everyone else knows
and I don't? Is this one of those 'pain-in-the-backside' things that
we just have to put up with and end up implementing default
constructors and invariant checks just so we can do the other things
we need to do?
Thanks for any help anyone can offer...
--rob