简体   繁体   中英

How do I cast a base class pointer to a pointer of a class derived from it? C++

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

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 );

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM