简体   繁体   中英

C++ Overloaded Function and Subclasses

Suppose I have:

struct Vehicle {...}
struct Car : public Vehicle {...}

string A(Vehicle *v) { return "vehicle"; }
string A(Car *c) { return "car"; }

And I do this:

Vehicle *v = new Car();
cout << A(v);

Why does the compiler print out "vehicle"? After all, v points to a Car object.

The overloaded function A(Vehicle*) is a better match for argument of type Vehicle* . So the cout will print:

vehicle

Explanation:

The overloaded function resolution is done based on the static type of argument. And the static type of the argument v is Vehicle* . Therefore, the function A(Vehicle*) will be called.

"vehicle" 

gets printed out

This happens because the static type of v is a Vehicle. So the A defined for Vehicle gets used by the compiler.

The compiler uses dynamic type information when calling a member function to do virtual method calls. The keyword virtual is required. In this case the "this" pointer will be appropriately downcast at the appropriate override level.

However, outside of this special case the compiler won't downcast for you without an explicit dynamic_cast.

This is example of static binding. During compilation it is clear that string A(Vehicle *v) function will be called. Of course "vehicle" should be in output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM