简体   繁体   中英

Type Confusion in C++

I am referring to this link .

#include <iostream>
using namespace std;


class Base {}; // Parent Class

class Execute: public Base {   // Child of Base Class
public:
    virtual void exec(const char *program) 
    {
        system(program);
    }
};

class Greeter: public Base {   // Child of Base Class
public:
    virtual void sayHi(const char *str) 
    {
        cout << str << endl;
    }

};


int main() {

    Base *b1 = new Greeter();
    Base *b2 = new Execute();
    Greeter *g;

    g = static_cast<Greeter*>(b1); // Safe Casting to the same type "Greeter"
    g->sayHi("Greeter says hi!"); // String passed to sayHi() function

    g = static_cast<Greeter*>(b2); // Unsafe Casting to sibling class "Execute"
    g->sayHi("/usr/bin/xcalc"); // String passed to exec() function 
                                    // which will turn into a command to execute calculator

    delete b1;
    delete b2;
    return 0;
}

My question is about the statements:

g = static_cast<Greeter*>(b2);
g->sayHi("/usr/bin/xcalc");

b2 is an instance of type Execute . The b2 instance will have a vpointer to vtable containing entry for exec() . When the next statement calls g->sayHi(..) , how will the vtable be used to look up which function to call?

Referring to link , it states that:

the function name is used as index to the vtable to find the correct (most specific) routine to be executed

If the name of the function is used, then how is the name sayHi found in the vtable for type Execute ?

The name is mapped to an index in the vtable at compile time, so at run time the function call is just an array lookup.

The code in question results in Undefined Behavior, because a b2 is not a Greeter* . (A dynamic_cast would return nullptr .) One possible outcome is that the vtable entry for sayHi will have the same index as the exec function in Execute , so while the source code looks like it will call sayHi , it will actually call exec . Or it could crash.

But anything can happen.

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