N
I wouldn't agree. There are several things I see with this solution
that make me question it.
1 - Although the OP used "NestedStruct" as his name, he didn't actually
nest it. There's nothing here that tells us that there's no use for
"NestedStruct" outside of "TopStruct".
2 - We don't know that even if #1 is as we are assuming (only used
within the context of TopStruct) that it will continue to be so.
3 - TopStruct cannot be used as a value type except when it doesn't have
the "NestedStruct". It must always use pointer semantics.
The first and second problem are not inherent problems, at least not in
this very specific case (could be in other cases), but it does force all
clients of "NestedStruct" to also hold uninteresting information
inherited from "TopStruct".
The third issue may or may not come up, but there's no reason to force
pointer semantics on something that doesn't necessarily need it.
You may buy some pointer safety with this design but there's a better
option that will provide that same safety without the inheritance,
dynamic_cast, and will give the OP what we should always prefer over
inheritance: composition. That better method is boost:ptional.
struct NestedStruct { std::string x; };
struct TopStruct
{
std::string ggg;
boost:ptional<NestedStruct> nested;
};
while ( top = GetStructs() )
{
if (top->nested)
do_things_with_nested(*top->nested);
}
* Noah Roberts:
For 1, if that is a problem, you simply don't make NestedStruct directly the
derived class but rather the derived class will have such a member
2 is IMHO a good point, but it depends on whether the NestedStruct is meaningful
on its own.
For 3 the "cannot" is incorrect -- note the assumption of staying the same way
during lifetime -- but using Boost optional is as you point out far more
convenient when that assumption does not hold /and/ you want value semantics.
Summing up, if there is a good chance that NestedStruct might be useful on its
own in the future, it should perhaps be written as a separate class.
But on the other hand, premature generalization can lead to wasted work, so it
depends on the concrete case and to some degree personal preference.
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.