2

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

Habit
  • 839
  • 3
  • 9
  • 21
  • 1
    "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?" You wouldn't. You'd use [tag:polymorphism]. – johnsyweb May 04 '13 at 02:50
  • 1
    If it's virtual you don't need a cast. Otherwise, `static_cast` and `dynamic_cast` should work. – Pubby May 04 '13 at 02:51
  • @Johnsyweb hmm can you explain that? I can't find a simple explanation. They all seem to go into pretty great detail. – Habit May 04 '13 at 02:58
  • Polymorphism is fundamental to understanding object-oriented programming in C++. A brief explanation in the comments would not suffice. I recommend reading [a good book](http://stackoverflow.com/q/388242/78845). – johnsyweb May 04 '13 at 03:04

2 Answers2

3

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 );
Mikael Persson
  • 18,174
  • 6
  • 36
  • 52
3

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 1
    Ok. Yeah I have multiple virtual. I'll probably post a new question here in a bit that explains my actual problem. With code and such. Thanks – Habit May 04 '13 at 03:01
  • 1
    You're not limited to just dynamic_cast though, as @Mikael Persson 's answer shows. Though I do like that you mention possibly needing to enable RTTI, which he does not mention. – leetNightshade May 04 '13 at 03:02