fork(2) download
  1. #include <iostream>
  2.  
  3. class Base {
  4. public:
  5. char const* address() const { return (char const*)dynamic_cast<void const*>(this); } // uses RTTI
  6. size_t offset() const { return this->address() - (char const*)this; }
  7. virtual size_t size() const { return sizeof(Base); } // to be overriden
  8.  
  9. };
  10.  
  11. class Derived: public Base {
  12. public:
  13. virtual size_t size() const { return sizeof(Derived); } // to be overriden
  14. private:
  15. int a;
  16. int b;
  17. };
  18.  
  19. int main() {
  20. Base base;
  21. Derived derived;
  22.  
  23. std::cout << (void*)&base << ": " << (void*)base.address() << ", " << base.offset() << ", " << base.size() << "\n";
  24.  
  25. std::cout << (void*)&derived << ": " << (void*)derived.address() << ", " << derived.offset() << ", " << derived.size() << "\n";
  26. }
Success #stdin #stdout 0.01s 2724KB
stdin
Standard input is empty
stdout
0xbffa28e8: 0xbffa28e8, 0, 4
0xbffa28dc: 0xbffa28dc, 0, 12