Re: Casting to a derived class
PGK 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.
You can cast a base* to a derived* if the base* actually points to
the base* subobject of a derived* object. For example:
Derived d;
Base* pb = &d;
Derived* pd = static_cast<Derived*>(pb); // OK
It doesn't matter whether the class has member variables or not,
at least from the viewpoint of the standard.
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;
}
This is wrong, because there is no object of type der here actually.
The compiler cannot give a warning because the cast can be sometimes
valid and sometimes not, and the compiler cannot tell at compile-time
whether the cast is valid or not. For example:
inline Derived* cast(Base* p) { return static_cast<Derived*>(p); }
// OK or not?
Base b;
Derived d;
Derived* pd = cast(std::rand() % 2 ? &b : &d);
--
Seungbeom Kim
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]