dynamic_cast<target-class>(val)
val should be a pointer or reference to class instance.
target-class should be a pointer or reference to a class type.
C, casting values of other types to or from values
of type C is often useful.
Given the class big_int,
big_int bi = "1000000000000000000000000000";
string msg = string("128! = ") + bi;
Other types convert to and from big_ints in the same way.
C::C(const T & tval)
big_int::big_int(const string & str) { ... }
big_int bi("100000000000000000000000000");
bi = "10";
"10" gets converted to a string, which gets converted to a big int, which
gets assigned by bi.
explicit keyword can prevent these problems.
explicit C::C(const T & tval);
explicit big_int::big_int(const string & str) { ... }
big_int bi("10"); // Counts as explicit.
bi = "20"; // Wrong - no explicit call.
bi = big_int("30"); // Ok - explicit call.
T, define a class
operator that casts to T.
C::operator target-type ()
big_int::operator string () { ... }
cout << static_cast<string>(bi) << "\n";
explicit.
string big_int::get_string(void) const { return ...; }
cout << bi.get_string() << "\n";
This page last modified on 22 November 2002.