Gabriel
Gabriel

Reputation: 13

C++ Detecting an implicit cast of 0 to a class

I am calling a function in a API that returns a Answer object. Under some conditions, the API will return EMPTY_answer, which is defined as such:

 #define EMPTY_answer ((Answer)0)

of course, attempting to access a Answer variable or function from an EMPTY_answer object crashes the application.

Trying to test for it using if(lAnswer == EMPTY_answer) also crashes the application. Is there any way to detect if the API is returning EMPTY_answer?

Edit:

I didn't code the api and I can't modify it in any way, I'm just digging through .h files trying to figure this out. And yes, I am aware that casting 0 to a class is a bit too creative to put it mildly. I just noticed that the == operator is overridden

(...)
class ExportedByJS0CORBA Answer
{
   (...)
   int __stdcall operator==(Answer *ipt) const;
}

the function being called is

static SubClassOfAction Query();

I'm simplifying names and quite a few layers of inheritance To be more precise, it crashes with a Segmentation Fault.

Upvotes: 1

Views: 166

Answers (3)

AnT stands with Russia
AnT stands with Russia

Reputation: 320461

If Answer is a class type, as the text of your questions suggest, then (Answer) 0 will construct a temporary Answer object using the constructor that accepts 0 as an argument (apparently such constructor exists). In this case attempting to access the members of that object will not crash anything, unless Answer class is specifically implemented to crash in this case (intentionally or unintentionally). So your "Of course..." claim makes no sense whatsoever. There's no immediate reason for such code to crash.

If you observe crashed in someAnswer == EMPTY_answer comparison, that would either mean that the implementation of == operator is buggy, or that either the LHS or the RHS are not valid objects. For example, it might turn out that it is illegal (by design) to construct an Answer object by conversion from 0. If so, then you should simply stop using (Answer) 0 in your code and find another, correctly supported object value to indicate an empty answer.

Upvotes: 2

Mark Ransom
Mark Ransom

Reputation: 308158

Instead of doing a very ugly cast which is almost guaranteed to trigger undefined behavior, just make a static global variable which is used as the "empty" answer. You don't need to use this object in any way, just make it exist so it can be used as a sentinel.

In Answer.h:

extern const Answer EMPTY_answer;

In Answer.cpp:

const Answer EMPTY_answer;  // use any constructor parameters that will be appropriate

Upvotes: 4

tenfour
tenfour

Reputation: 36896

your original method of just checking for EMPTY_answer is the right way to solve this. Your real problem is why that crashes. What type is lAnswer? Or Answer for that matter... you can't cast 0 to a class like that.

Upvotes: 0

Related Questions