I have a question regarding the resolving timing of a C++ virtual function. From chapter OOP in C++ Primer, it mentioned that:
Calls to Virtual Functions May Be Resolved at Run Time When a virtual function is called through a reference or pointer, the compiler generates code to decide at run time which function to call. The function that is called is the one that corresponds to the dynamic type of the object bound to that pointer or reference.
I understand what the above statement describes: when a virtual function is executed, which version is really resolved depends on the actual type of calling pointer/reference. If the actual type of pointer/reference is base class, the virtual function of base class is the one actually being run, vice versa. It obviously needs to be done in run time.
However, the example following by the above statement in C++ primer has confused me for a while:
double print_total(ostream &os, const Quote &item, size_t n)
{
// depending on the type of the object bound to the item parameter
// calls either Quote::net_price or Bulk_quote::net_price
double ret = item.net_price(n);
}
// Quote is base class, Bulk_quote is derived class
Quote base("0-201-82470-1", 50);
print_total(cout, base, 10); // calls Quote::net_price
Bulk_quote derived("0-201-82470-1", 50, 5, .19);
print_total(cout, derived, 10); // calls Bulk_quote::net_price
My questions are:
- For my understanding, in this example, compiler is able to know in compile time the "real type" of instance base and instance derived as they are just declared obviously in sketch! So, I think the resolved timing of this example can be in compile time. Am I right about that?
- Can resolved timing of virtual functions be compile time? Or as a matter of convenience, C++ just makes all virtual functions resolved in run time? Since C++ primer says: Calls to Virtual Functions May Be Resolved at Run Time, I am not quite sure if run time is all the case.
I think to really understand the resolved time of virtual functions is very important to every C++ user. I tried to find the knowledge about compile time/run time but none of them can help me figure out my question. Do anyone have any thoughts on my questions. Thank you in advance!