Reputation: 845
I pass 2 pointers of (class A) to it's derived class (class B) via parameter.
One of the pointers needs to be of class B so that I can call methods that were declared in B.
How would I do that?
Doesn't a static cast only let you do it the opposite way? (B to be dynamically casted to type A). I've been told not to do c-style casts. And reinterpret casts can be dangerous?
The only other one that I can think of is a static cast. Is that what I would need here?
Thanks
Upvotes: 2
Views: 2221
Reputation: 727047
In general, you want to avoid situations like that by using only the member functions declared virtual
in the base. If you must cast a pointer to a derived class, make sure that the base class has at least one virtual
function (any function or a destructor would be enough), and then use dynamic_cast<T>
:
BaseClass *bp = new DerivedClass();
...
DerivedClass *dp = dynamic_cast<DerivedClass*>(bp);
if (!dp) {
cerr << "Not a derived class!" << endl;
}
If bp
points to a DerivedClass
, dynamic cast succeeds; otherwise, it fails, and returns a null pointer.
You may need to compile with special flags to enable RTTI support.
Upvotes: 3
Reputation: 18572
You can use either static_cast
or dynamic_cast
for this purpose. The difference between the two is that dynamic_cast
will check, at run-time, whether the pointer actually points to an object of the derived class (this requires that there is at least one virtual
member function (incl. the destructor) in the base class). If you can be sure that the cast is possible, then static_cast
will just do it without a run-time check.
The syntax is:
B* p_b = static_cast< B* >( p_a );
// or:
B* p_b = dynamic_cast< B* >( p_a );
Upvotes: 3