I am learning C++ and if I have classes
class Core {...}
class Grad: public Core {...}
then
Core* p;
Core& ref;
may be Grad objects which is not determined at compile time but at runtime hence the use of virtual functions to let such an object use its own method if it is overriden.
My question is: why can the compiler not find this out at compile time?
I read the most upvoted answer on SO about runtime vs compile time but it did not cover my question. Another one explains that C++ just does not do this during compilation time but I wonder why this is the case it seems easy to do a type check for inheritance hierarchies.
5
My question is: why can the compiler not find this out at compile time?
Take this case for example:
Core core;
Grad grad;
bool b = GetFromUser(); // get boolean input from the user
Core& ref = b ? core : grad;
The compiler cannot determine at compile time if ref
refers to a Core
instance or a Grad
instance. It will be determined at runtime based on the input from the user.
A similar example can be constructed using a pointer instead of a reference.
There could be a case where the pointer/reference is assigned to an object returned from a function which can be (1) dependant on some runtime condition or (2) not visible at all to the compiler in this translation unit.
On the other hand in some other cases it might be possible for the compiler to determine this at compile time.
Bottom line:
The compiler cannot always determine it at compile time.
1