How does the C++ compiler know which implementation of a virtual function to call?

后端 未结 6 2025
北恋
北恋 2020-12-03 00:10

Here is an example of polymorphism from http://www.cplusplus.com/doc/tutorial/polymorphism.html (edited for readability):

// abstract base class
#include <         


        
6条回答
  •  醉梦人生
    2020-12-03 00:41

    cout << ((Polygon *)0x12345678)->area() << endl;
    

    This code is a disaster waiting to happen. The compiler will compile it all right but when it comes to run time, you will not be pointing to a valid v-table and if you are lucky the program will just crash.

    In C++, you shouldn't use old C-style casts like this, you should use dynamic_cast like so:

    Polygon *obj = dynamic_cast(0x12345678)->area();
    ASSERT(obj != NULL);
    
    cout << obj->area() << endl;
    

    dynamic_cast will return NULL if the given pointer is not a valid Polygon object so it will be trapped by the ASSERT.

提交回复
热议问题