Q:

How to check if a struct has a certain variable?

So I have the following two structs. Let's say I have a void pointer that, depending on the situation, will point to either bag or apple. How do I check which struct type it is pointing to so I can dereference it?
struct product
{
        int price;
        string name;
};

struct fruit : product
{
        int weight;
};

product bag;
fruit apple;

edit: so this is just the simplified version of code i'm working with at my new job. I need to check for a certain variable, but like the weight variable in fruit, sometimes it is passed with a void pointer and sometimes it isn't. There's a lot of code already so changing it from void pointers would be too much. I need to check if the weight variable exists, and then do something based on what value is in it.

A:

Don't use void* in C++. There is almost never a case when it is valid to use void* as a real data object in client code.
In your case, instead of void*, you need to use product*, and declare destructor of product* virtual. This way you will be able to test for the actual object using dynamic_cast.
Even a better option is to carefully design your classes, introduce the proper virtual functions and make sure you never need to know the actual type of the object. But this is a topic of a separate question.

