Reputation: 30895
I have a struct that contains many members and also an operator overloading of == like this :
struct Adjustment {
ObjectNumber aD;
Foo afoo;
bool operator == (const Adjustment& aAdjustment) const
{ return (aAdjustment.ID == ID); }
};
and when in code I have:
if(someAdjustment == NULL)
it gives me :
error C2678: binary '==' : no operator found which takes a left-hand operand of type 'Unit::Adjustment' (or there is no acceptable conversion)
So my question is, how can I check if this struct is set , without changing its code?
Upvotes: 0
Views: 10891
Reputation: 33536
In C++, a "reference" denoted by &
implies that the caller of your method is obligated to provide you with an object instance. There is no (NORMAL) way to call your method without an object. You are free to assume that you if your function is called, the aAdjustement will be set to something.
However, there are two gothas here:
(1) It will be set to something, but will that 'something' be meaningful? Is a Adjustement structure completely zeroed-out a valid value for your function? If not - then you may test that instead test nulliness. If any structure value combinations are invalid - use this as the discriminator. If all possible values are valid - then there's nothing to be checked.
(2) If you know the dark ways (tm), you actually CAN PASS a null-reference to this function. So your code is not "safe from nulls" just because "you used reference&". However, as I said, with use of & you clearly state that you disallow nulls. A caller that knows the dark ways(tm) may only blame himself when your function crashes.
disclaimer: "normal" and "the dark ways" are just buzzwords to hide extra complexity of a real professional explanation. If you play a bit with casting and */& operators, you will quickly discover how to get i.e. "int& boom" that would point to a zero-address. This is not so "dark" nor "magic", it's plain feature of the language and platform. However, (A) novice programmers and even somewhat experienced programmers tend to not know that references can be null, and (B) the convention of &-means-dont-pass-null is really well known and settled, so (A+B) please adapt to the convention and feel free to use it where adequate.
Upvotes: 2
Reputation: 70939
You may only compare a pointer to NULL
. An Adjustment itself will never be NULL.
Upvotes: 2