Re: Checking for null pointer for structure
* Alf P. Steinbach:
* GrzybSon:
Hello,
I have got two nested structures:
struct TopStruct
{
char * ggg;
union
{
NestedStruct nested;
} param;
};
struct NestedStruct
{
InnerStruct inner;
};
struct InnerStruct
{
char * txt;
}
How to check if field nested of type NestedStruct is not null?
Some code given:
TopStruct * top;
while ( (top = GetStructs()) != NULL)
{
// ...
if (top->nested != NULL) // this gives me compiler error c2678
binary '!=' : no operator found which takes a left hand operand of type
{
// do something
}
}
What is wrong?
The design. Sorry, that's brutal, and even though I'm pretty old I've
not yet learned how to say such things in some acceptable way. So I just
go for the straightforward, hoping people will forgive me since the info
is good, yes?
Forgot to add, the direct cause of the compilation error is that the code
compares a non-pointer, namely a NestedStruct, to zero.
C++ provides enough magic to make that work, i.e. NestedStruct could /define/ a
meaning for comparision with zero, in various ways.
But that's advanced and not relevant here.
Okay, others will probably comment on your char*'s, recommending instead
std::string, but let's look at the design.
As I understand it you want TopStruct to have an optional NestedStruct.
Some TopStruct-s will have a NestedStruct, some will not.
The question is, will any given TopStruct ever /acquire/ or /lose/ a
NestedStruct, or is a TopStruct created with/without a NestedStruct and
staying that way for its lifetime?
If it stays that way for its lifetime, then a natural solution is to use
inheritance.
It then goes like this:
struct TopStruct
{
virtual ~TopStruct() {} // You need /some/ virtual method.
std::string ggg;
};
struct WithNestedStruct: TopStruct // Inheritance
{
std::string text;
};
...
while( (top = GetStructs()) != 0 )
{
if( WithNestedStruct* p = dynamic_cast<WithNestedStruct*>( top ) )
{
// Do things with p
}
}
There are more advanced techniques to avoid the 'if' or 'case', that is,
to avoid explicit type discrimantion, and generally those techniques are
based on using virtual methods. In short, you let the effect of a call
to method depend on the object at hand. But perhaps first try if you can
get the above to work, assuming of course that the assumption of
TopStruct-s staying the way they're created, holds.
If that assumption does not hold, then use a pointer in TopStruct, and
then take care not to copy those structs, or if you do, decide on what
to do with pointer.
Cheers,
- Alf