C++ :(

SSM

Registered
hi all

i've a little question ... hope i can get the answer here :)

i'm required to write a C++ program using (time polymorphism) ,that is using pointers that point to classes ( user defined classes)

also...i'm required to downcast these pointers using the operator (dynamic_cast) which is part of the C++ run-time type information (RTTI) feature.

the problem is that don't know how to use this operator,,, (dynamic_cast)

how can i use it in my program :confused:

can anyone help :(
 
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vccelng/htm/express_72.asp

(I know, it's a Microsoft site, but that's the first thing that came up in a Google search and it's quite useful)

dynamic_cast < type-id > ( expression )

If type-id is a pointer to an unambiguous accessible direct or indirect base class of expression, a pointer to the unique subobject of type type-id is the result. For example:

Code:
class B { ... };
class C : public B { ... };
class D : public C { ... };

void f(D* pd)
{
  C* pc = dynamic_cast<C*>(pd);  // ok: C is a direct base class
                      // pc points to C subobject of pd

  B* pb = dynamic_cast<B*>(pd);  // ok: B is an indirect base class
                      // pb points to B subobject of pd
  ...
}
 
You can also use dynamic_cast to test if a class can be downcasted.
If you have class A, class B which inherits from class A, and class C which doesn't inherit then you could do something like this:

Code:
if(dynamic_cast<A*>(pB))
    cout << "B* can be cast to A*" << endl;//this will print

if(dynamic_cast<A*>(pC))
    cout << "C* can be cast to A*" << endl;//this won't print
 
Back
Top