Yes, I know C style casts are bad news, but I am trying to pinpoint the only places where they can be used without danger...
I am proposing the following to see where the standard stands on. First, assume we have monomorphic classes as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
namespace MonoMorphicSample
{
class Base
{
};
class Derived : public Base
{
};
void Call( Base* pBase)
{
// assume we know pBase points to a Derived... then we can (??) do this:
Derived* pDer = (Derived*)pBase;
// and use pDer here
// .....
}
}
Second, say we have the same but with polymorphic classes:
namespace PolyMorphicSample
{
class Base
{
public:
virtual ~Base() = default;
};
class Derived : public Base
{
public:
virtual ~Derived() = default;
};
void Call( Base* pBase)
{
// assume we know pBase points to a Derived... then we can (??) do this:
Derived* pDer = (Derived*)pBase;
// and use pDer here
// .....
}
}
Are the 2 examples ALWAYS correct? (i.e. can we in these cases use the C style cast without problem?)?
NOTE: if Derived inherited from more than one class, then obviously non of these cases would work -- not good idea to use C style cast when in multiple inheritance..
There is no way to know whether the pointer passed into the function is a Derived* or a Base* (or a pointer to some other class also derived from Base). If you know that the pointer is a pointer to Derived, then why not make the argument a Derived*?
If you want to downcast from Base* to Derived*, use
Derived* pDer = dynamic_cast<Derived*> pBase;
If pDer ends up non-NULL, then pBase is pointing to a Derived object. Otherwise, pDer will come up NULL.
Yes I know this. But actually, even if we know pBase points to a pDerived, then if the definition of Derived is not available where the C Style cast is made, then the cast will be wrong at least when Derived has more than one superclass and the first superclass is a class other than Base.
This was my point.
As far as I can tell, if Derived only has one superclass or has Base as the first superclass then the C style cast will work (even though static_cast is safer).
Yes, I know C style casts are bad news, but I am trying to pinpoint the only places where they can be used without danger...
IMO any cast can never be used without danger, but C++ casts are much safer than the C cast, that is why C++ casts were implemented. C style casts are not type safe and by using them you can create a cast that compiles but fails to work as expected. Don't forget that there are more C++ style casts other than static_cast.