What will be printed out as a result of the following code execution?
#include <iostream>
class A
{
public:
    A() 
    { 
        std::cout << "A()"; 
    }
    void memget()
    {
        std::cout << sizeof(*this);
    }
    virtual void f()
    {
        std::cout << "f()";
    }
    virtual void f2()
    {
        std::cout << "f2()";
    }
    virtual ~A() 
    {
        std::cout << "~A()";
    }
};
struct VPTR
{
    void (*function0)(void);
    void (*function1)(void);
    void (*function2)(void);
};
int main()
{
    A* ob = new A;
    VPTR** vPtr = reinterpret_cast<VPTR**>(ob);
    (*vPtr)->function0();
    ob->memget();
    delete ob;
    return 0;
}
Explanation
vPtr points to a memory area containing the address of the virtual function table, in VS2010, the virtual function table takes 4 bytes of memory - sizeof(*void), the table stores the addresses of virtual functions
1) the constructor of the object in the heap is called
2)vPtr is initialized with a pointer to the address of the ob object table
3) the function f() is called at the address passed to the vPtr structure
4) the memget() function is called, which stores the size of the object
5) virtual destructor is called

Слідкуй за CodeGalaxy

Мобільний додаток Beta

Get it on Google Play
Зворотній Зв’язок
Cosmo
Зареєструйся Зараз
або Підпишись на майбутні тести