Is "IS_A" a boolean operator?
I want to find out what type of class a pointer is pointing to, and I don't know how... tell me if I'm right or wrong and inform me correctly please!
Is "IS_A" a boolean operator?
I want to find out what type of class a pointer is pointing to, and I don't know how... tell me if I'm right or wrong and inform me correctly please!
fromdynamic_cast
dynamic_cast is exclusively used with pointers and references to objects. It allows any type-casting that can be implicitly performed as well as the inverse one when used with polymorphic classes, however, unlike static_cast, dynamic_cast checks, in this last case, if the operation is valid. That is to say, it checks if the casting is going to return a valid complete object of the requested type.
Checking is performed during run-time execution. If the pointer being casted is not a pointer to a valid complete object of the requested type, the value returned is a NULL pointer.
class Base { virtual dummy(){}; };
class Derived : public Base { };
Base* b1 = new Derived;
Base* b2 = new Base;
Derived* d1 = dynamic_cast<Derived*>(b1); // succeeds
Derived* d2 = dynamic_cast<Derived*>(b2); // fails: returns NULL
http://www.cplusplus.com/doc/tutorial/tut5-4.html
Here is a sample of how this can be accomplished using the MFC.
This will only work with the classes that are derived from CObject. You might get an idead of how to implement this without the MFC. I have no idea of how they do it... just thought you might be interested...
BTW - You can use MFC in a console app...
// in .H file
class CPerson : public CObject
{
DECLARE_DYNAMIC( CPerson )
public:
CPerson(){};
// other declaration
};
// in .CPP file
IMPLEMENT_DYNAMIC( CPerson, CObject )
void SomeFunction(void)
{
CObject* pMyObject = new CPerson;
if(pMyObject->IsKindOf( RUNTIME_CLASS( CPerson ) ) )
{
//if IsKindOf is true, then cast is all right
CPerson* pmyPerson = (CPerson*) pMyObject ;
...
delete pmyPerson;
}
...
delete [MyObject];
}