Skip to content

Instantly share code, notes, and snippets.

@h1mesuke
Created July 28, 2010 23:34
Show Gist options
  • Save h1mesuke/496741 to your computer and use it in GitHub Desktop.
Save h1mesuke/496741 to your computer and use it in GitHub Desktop.
C++ - Sample usages of xxx_cast()
#include <iostream>
using namespace std;
class Base {
virtual void f() {};
};
class Derived: public Base {
};
int main(int argc, const char *argv[])
{
// dynamic_cast
{
Base *bp, b;
Derived *dp, d;
cout << endl;
cout << "== dynamic_cast" << endl;
bp = &b;
if (dp = dynamic_cast<Derived *> (bp)) {
cout << "cast bp(&b) to dp: success" << endl;
} else {
cout << "cast bp(&b) to dp: failure" << endl;
}
bp = &d;
if (dp = dynamic_cast<Derived *> (bp)) {
cout << "cast bp(&d) to dp: success" << endl;
} else {
cout << "cast bp(&d) to dp: failure" << endl;
}
}
// const_cast
{
int i = 10;
const int *p = &i;
int *q;
cout << endl;
cout << "== const_cast" << endl;
//*p = 20;
//-> error
q = const_cast<int *> (p);
*q = 20;
cout << "*p = " << *p << endl;
}
// reinterpret_cast
{
int i;
char *p = "hello";
cout << endl;
cout << "== dynamic_cast" << endl;
i = reinterpret_cast<int> (p);
//-> warning: deprecated conversion from string constant to ‘char*’
cout << "i = " << i << endl;
}
// static_cast
{
float f = 3.14;
int i;
cout << endl;
cout << "== static_cast" << endl;
i = static_cast<int> (f);
cout << "i = " << i << endl;
}
return 0;
}
// vim: filetype=cpp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment