Matra Divat wrote:
We can assume ClassB is derived from ClassA.
In that case fix the function prototype:
void app::f(ClassB b) {
}
Casting a type is always a consequence of inappropriate interface design. If you have the ability to fix the interface, do that before having to introduce type casts!
If for any reason you cannot avoid the cast, the safe and correct way is not to assume, but to verify. Doing so is possible using
dynamic_cast
[
^], but this cast only works on pointers and references. In your case, you should be doing sth like this:
class ClassA {
};
class ClassB : public class ClassA {
};
void app::f(ClassA a) {
ClassB* pb = dynamic_cast<ClassB*>(&object);
assert (0 != pb); if (0 == pb) {
}
else {
ClassB& b = *pb; }
}