"Jakob Bieling" <ne*****@gmy.net> wrote...
I have a question about casting and using the casted pointer: Suppose
I have a 'base' class and a 'derived' class (which is derived from 'base').
Now I have this scenario:
base* p1 = new base ();
base* p2 = new derived ();
derived* d1 = (derived*) p1;
derived* d2 = (derived*) p2;
Does the cast itself already produce undefined behaviour?
No.
Or will I get
there when using 'd1'?
Yes.
I am asking because I have a similiar scenario, where
the casted pointer is used in an if-statement, like this:
if (p2->is_derived () && d2->func_only_present_in_derived_class ())
{
}
If the function 'is_derived' doesn't attempt to interpret the pointer
_as__if_ it points to an object of class 'derived', but uses some other
mechanism (that actually works), you should be fine.
I can imagine that these classes should work:
class base {
public:
virtual ~base() {}
virtual bool is_derived() const { return false; }
};
class derived: public base {
public:
bool is_derived() const ( return true; }
bool func_only_present_in_derived_class();
};
However, with all that said, the rule of thumb still stands: never use
C-style casts (like you did in your post). There is no real need in
them. If you are convinced that you cannot solve your problem without
a C-style cast, your approach is incorrect.
Victor