
#include <iostream>

class Object {
protected:
  typedef int test_type;
public:
  Object() : i(2) {}
  virtual ~Object() {}
  test_type i;
};

// don't use virtual inheritance and it works
class Base : virtual public Object {
public:
  Base() : Object() {
    std::cout << "RTTI memory offset (in test_type units) in constructor: " 
	      << rtti_offset() << std::endl;
    // Uncomment this to crash the application 
    /* std::cout <<  "RTTI member access in constructor (1): " 
       << rtti_access() << std::endl; */
  }
  virtual ~Base() {}
  size_t rtti_offset(void);
  test_type rtti_access(void);
};

size_t Base::rtti_offset(void) {
  Object* objectbase_=static_cast<Object*>(this);
  Base *obj = dynamic_cast<Base*>(objectbase_);

  return (reinterpret_cast<test_type*>(obj) 
	  - reinterpret_cast<test_type*>(this));
}

Object::test_type Base::rtti_access(void) {
  Object* objectbase_=static_cast<Object*>(this);
  Base *obj = dynamic_cast<Base*>(objectbase_);

  return obj->i;
}

class Derived : public Base {
public:
  Derived() : Base() {}
protected:
  // Comment this and it works again !
  test_type x;
}; 

int main(int argc, char	**argv)
{
  using namespace std;

  // First with a Base object
  cout << "1. Testing a Base object" << endl; 
  Base b;
  cout	<<  "RTTI memory offset in main: " << b.rtti_offset() << "\n"
	<<  "RTTI member access in main (2): " << b.rtti_access() 
	<< "\n" << endl;
  
  // Then with a Derived object
  cout << "2. Testing a Derived object" << endl; 
  Derived w;
  cout	<<  "RTTI memory offset in main: " << w.rtti_offset() << "\n"
	<<  "RTTI member access in main (2): " << w.rtti_access() 
	<< "\n" << endl;
  
  return 0;
}

