#include <iostream>
class Base {
public:
char const* address() const { return (char const*)dynamic_cast<void const*>(this); } // uses RTTI
size_t offset() const { return this->address() - (char const*)this; }
virtual size_t size() const { return sizeof(Base); } // to be overriden
};
class Derived: public Base {
public:
virtual size_t size() const { return sizeof(Derived); } // to be overriden
private:
int a;
int b;
};
int main() {
Base base;
Derived derived;
std::cout << (void*)&base << ": " << (void*)base.address() << ", " << base.offset() << ", " << base.size() << "\n";
std::cout << (void*)&derived << ": " << (void*)derived.address() << ", " << derived.offset() << ", " << derived.size() << "\n";
}
ICAgICNpbmNsdWRlIDxpb3N0cmVhbT4KCiAgICBjbGFzcyBCYXNlIHsKICAgIHB1YmxpYzoKICAgICAgY2hhciBjb25zdCogYWRkcmVzcygpIGNvbnN0IHsgcmV0dXJuIChjaGFyIGNvbnN0KilkeW5hbWljX2Nhc3Q8dm9pZCBjb25zdCo+KHRoaXMpOyB9IC8vIHVzZXMgUlRUSQogICAgICBzaXplX3Qgb2Zmc2V0KCkgY29uc3QgeyByZXR1cm4gdGhpcy0+YWRkcmVzcygpIC0gKGNoYXIgY29uc3QqKXRoaXM7IH0KICAgICAgdmlydHVhbCBzaXplX3Qgc2l6ZSgpIGNvbnN0IHsgcmV0dXJuIHNpemVvZihCYXNlKTsgfSAvLyB0byBiZSBvdmVycmlkZW4KCiAgICB9OwoKICAgIGNsYXNzIERlcml2ZWQ6IHB1YmxpYyBCYXNlIHsKICAgIHB1YmxpYzoKICAgICAgdmlydHVhbCBzaXplX3Qgc2l6ZSgpIGNvbnN0IHsgcmV0dXJuIHNpemVvZihEZXJpdmVkKTsgfSAvLyB0byBiZSBvdmVycmlkZW4KICAgIHByaXZhdGU6CiAgICAgIGludCBhOwogICAgICBpbnQgYjsKICAgIH07CgogICAgaW50IG1haW4oKSB7CiAgICAgIEJhc2UgYmFzZTsKICAgICAgRGVyaXZlZCBkZXJpdmVkOwoKICAgICAgc3RkOjpjb3V0IDw8ICh2b2lkKikmYmFzZSA8PCAiOiAiIDw8ICh2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