Domanda

In this scenario where classes DeriA and DeriB inherit from Base:

class Base
class DeriA : public Base
class DeriB : public Base

std::list<Base> objects;

Is it possible to check what type of class is being inherited from each member of the objects list? I've tried using static_cast within a try/catch statement in order to check if a certain member of objects is a particular type as seen here:

try
{
    DeriA tempA = static_cast<DeriA>(*objects_iterator);
    std::cout << "Found A" << std::endl;
} catch(std::bad_cast e)
{
    // Dealing with the exception
    std::cout << "Found B" << std::endl;
}

However this always outputs "Found A" regardless of whether or not the object that was being accessed is DeriA or DeriB. Could anyone help shed some light as to why?

È stato utile?

Soluzione

If you have a Base* pointer you can dynamic_cast<DeriA*>. The result will be the cast object or NULL if it is not a DeriA.

However, you are dealing with values. A Base (not Base*) that you store in the list will always only be a Base and not a derived object. If you ever had a DeriA that you put in there, you probably sliced the rest of at some point.

Altri suggerimenti

From what little examples I saw, most using std::bad_cast exception are using dynamic_cast. Check this example out and see if dynamic_cast can help you. There is a requirement with dynamic_cast to have polymorphic functions, but you'll figure that out.

http://en.cppreference.com/w/cpp/types/bad_cast

-AP_

No you cannot properly do this. C++ has no build in concept of runtime type information, therefore it is not possible to cast around with static casts and see what happens.

Some compilers albeit implement a (horrible) RTTI system which allows you to make use of dynamic_cast. How ever the RTTI on most systems has unwanted side effects which causes large frameworks like Qt, etc to implement their own MACRO Magic RTTI system.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top