In some sources it is recommended to initialize the fields of an instance of the struct with zero. How will the following code fragment behave during compilation?
#include <iostream>
#include <typeinfo>
using namespace std;

class A {
public:
    virtual const type_info& Type() { return typeid(*this); }
};

struct B : public A {
public:
    int field1;
    int field2;
    int field3;
    B() {
        memset(this, 0, sizeof(B));
    }
};


int main()
{
    A* b = new B();
    cout << b->Type().name();

    return 0;
}
Explanation
The call of the memset function will clear not only the fields defined by the user but also the pointer to the table of virtual functions defined implicitly by the compiler. Thus, an attempt to access the virtual functions table by a null pointer will be made during execution.

Следи за CodeGalaxy

Мобильное приложение Beta

Get it on Google Play
Обратная Связь
Cosmo
Зарегистрируйся сейчас
или Подпишись на будущие тесты