shanjib_
shanjib_

Reputation: 65

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.

Upvotes: 0

Views: 731

Answers (3)

MSalters
MSalters

Reputation: 179799

Considering the comments (void* is entrenched in existing API's), the workaround would be a two-step cast. First, static_cast<product*> your void* pointer. Next, dynamic_cast that product* to fruit*.

You will need to add a virtual method to product as the dynamic_cast otherwise won't work.

Upvotes: 1

Guillaume Racicot
Guillaume Racicot

Reputation: 41760

With only void pointer you can't. Void pointers strip all type information from the variable. You must use something like std::type_index if you must know the type at runtime.

Upvotes: 0

SergeyA
SergeyA

Reputation: 62563

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.

Upvotes: 7

Related Questions