51

Possible Duplicate:
When should static_cast, dynamic_cast and reinterpret_cast be used?

With this C++ code,

char* a = (char*) b;

I got warning warning: use of old-style cast.

What would be the new-style cast?

Community
  • 1
  • 1
prosseek
  • 182,215
  • 215
  • 566
  • 871

2 Answers2

69

reinterpret_cast, static_cast, dynamic_cast and const_cast are the c++ cast alternatives.

  • const_cast to remove const/volatile from a const variable.
  • dynamic_cast to perform runtime validity checks when casting in between polymorphic types
  • static_cast to perform e.g up/down-cast in a inheritance hierarchy, but with no runtime checks, or to explicitly perform conversions that could be implicit (e.g. float to int)
  • reinterpret_cast to convert in between unrelated types.

Brief syntax example:

char* a = (char*) b; 
//would be 
char* a = static_cast<char*>(b);
//to remove the warning
Ingo Mi
  • 999
  • 12
  • 26
Erik
  • 88,732
  • 13
  • 198
  • 189
3

Read this topic to know about C++ style casts which come in various flavors:

When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?

Community
  • 1
  • 1
Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • 3
    I would argue that, if you think a link to another question is a suitable answer, then the question is a duplicate. – Chris Lutz Mar 09 '11 at 17:10
  • @Chris: After posting, I realized that. So I voted for closing it! – Nawaz Mar 09 '11 at 17:11
  • 1
    Depends, could he find the other question by searching for "old-style" and/or "new-style" cast? – Erik Mar 09 '11 at 17:12
  • 2
    @Erik: it doesn't depend, since if this question is marked a duplicate, it still stands as a search landing page. If it's a dupe, it should be marked a dupe, not answered again with identical answers just because the question is worded a bit differently. – Steve Jessop Mar 09 '11 at 17:24
  • Ahh ok, then I'll vote to close as well. – Erik Mar 09 '11 at 17:25