Why can't C++ compiler know a pointer is pointing to a derived class?
问题 I've just started learning about OOP in C++. I was wondering why is the virtual keyword needed to instruct the compiler to do late binding ? Why can't the compiler know at compile time that the pointer is pointing to a derived class ? class A { public: int f() { return 'A';} }; class B : public A { public: int f() { return 'B';} }; int main() { A* pa; B b; pa = &b; cout << pa->f() << endl; } 回答1: Regarding not knowing at compile time, it is often the case the behavior is only known at runtime