-2

As title, should I always use static_cast for C++ project; if I just want to handle the conversion from double to int and the conversion from a base-pointer to a derived-pointer. Is my thought correct?

Thanks all

Niall
  • 30,036
  • 10
  • 99
  • 142
gigir
  • 132
  • 1
  • 10
  • 1
    No, because `static_cast` doesn't do everything. Use the right cast for the job. – chris Sep 26 '14 at 13:59
  • 1
    There are four named casts in C++. Use the appropriate one in each case. Do note that a C style cast can do a job that none of the four named casts can. But in general, try to *avoid casts*. A good strategy to avoid casts is to not throw away information about type in the first place. – Cheers and hth. - Alf Sep 26 '14 at 14:00
  • If that was true then the other cast types would be redundant – EdChum Sep 26 '14 at 14:00
  • @Cheersandhth.-Alf What can C cast do that others can't? – Neil Kirk Sep 26 '14 at 14:20
  • @NeilKirk: it can cast to an otherwise inaccessible base (refererence or pointer) with proper address adjustment (like `static_cast` would do if it could handle this case). – Cheers and hth. - Alf Sep 26 '14 at 14:21

1 Answers1

0

Use static_cast for double to int conversions, but you probaby want dynamic_cast for base-pointer to derived-pointer.

Paul Evans
  • 27,315
  • 3
  • 37
  • 54