Re: Checking for null pointer for structure
On 17 Feb, 11:06, "Alf P. Steinbach" <al...@start.no> wrote:
* 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 c=
2678 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 t=
he
straightforward, hoping people will forgive me since the info is good, ye=
s?
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 s=
taying
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/ vir=
tual 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 bas=
ed on
using virtual methods. In short, you let the effect of a call to method d=
epend
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 the=
y're
created, holds.
If that assumption does not hold, then use a pointer in TopStruct, and th=
en take
care not to copy those structs, or if you do, decide on what to do with p=
ointer.
looks rather heavy machinary for a simple job...
inheritance for a simple optional sub-field?
but then we don't know why this nested structure is sometimes here
sometimes not.