Re: Casting to a derived class
On Jul 1, 12:52 am, PGK <graham.k...@gmail.com> wrote:
Hi all,
Is it safe to cast from a base class pointer to a derived one? My
guess is that it's not, though may go unnoticed if the derived class
has no member variables. Even if the class does have member variables,
there's a chance any reference to it may occur at an otherwise unused
memory location.
On the other hand, when I compile the code below I get no warnings.
Surely if this is less than savoury, the compiler should tell?
struct base {
int b;
};
struct der : public base {
int d;
};
int main(int argc, char *argv[]) {
der *pd = (der *)new base();
pd->d = 123;
}
{ quoted banner removed. don't quote extraneous material. tia., -mod }
You are using a C-style cast, which in this context is equivalent to
reinterpret_cast<der*>(new base()).
C-style casts are generally to be avoided, because they don't make it
clear what you are doing, but the C++ reinterpret_cast<> is a way of
saying "I the coder know best. The bits that you find in this memory
can be treated as an object of type 'der'".
With power comes responsibility. You were responsible for putting 123
into the wrong area of memory. reinterpret_cast<> is not type-safe.
If you do not trust yourself, there's static_cast<> and
dynamic_cast<>, which are type-safe. static_cast<> will throw up a
compilation error here, because it doesn't do downcasts.
dynamic_cast<> needs a virtual function and RTTI to work and then
should fail at run-time.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]