I find when writing functions (that use function overloading) that accept either a main class or subclass argument, that often implicit upcasting will occur (the subclass is upcasted as the main class and the main class function called). I don’t want this implicit upcasting to occur as it means subtle bugs sneak in and cause problems later on down the line.
I have searched on google for information on this, but there is little coherent information I can make use of and only indirect references to it.
How do I disable, stop or prevent implicit upcasting (and even downcasting) from occurring?
(I can’t supply any example code as this is a general problem that occurs from time to time).
No, this isn’t to do with methods (I would have specified methods) but functions.
No example code, but pseudo idea:
void Function(BaseClass &A);
void Function(SubclassClass &B);
Function(ASubclass); //Implicit upcasting occurs, calls BaseClass instead
The above situation won’t happen conventionally (say that the SubclassClass function gets knocked out/erased), but Subclass will be upcast to the BaseClass for use with the BaseClass function, instead of, say, reporting an error or generating a warning – either would be helpful as I don’t want implicit upcasting to occur.
Please don’t confuse upcasting with non-virtual method calls.
Upcasting:
A Base class pointer can always point to a derived class object as long as the derived class is
publicallyderived from the Base class. Eg: First Function Call.This upcasting happens implicitly.
If the derivation is
privatethis upcasting does not happen implicitly and compiler will issue an error.Though, using
privateinheritance is not the way to achieve this behavior. You should use private inheritance if it suits your design and it will implicitly gaurantee you that upcasting never happens implicitly.