0
class Base { int type; };
class Derived1 : public Base { ... };
class Derived2 : public Base { ... };
class Container
{
public:
    Derived1 f1;
    Derived2 f2;
};

Container c;

size_t offset = (size_t) static_cast<Base*>( &reinterpret_cast<Container*>(0)->f2 );
Base* base = reinterpret_cast<Base*>( (size_t) c + offset ); // ok

Base Container::* ptr = &Container::f2; // compile error!
base = c.*ptr;

Is the any valid method to get pointer to Base using pointer-to-member?

  • You are dereferencing a `nullptr`, therefore the code has undefined behavior. Maybe [`offsetof`](http://en.cppreference.com/w/cpp/types/offsetof) is what you want. – nwp Oct 12 '17 at 14:36
  • That `reinterpret_cast(0)` is officially UB. You shouldn't use it unless the implementation guarantees it's okay. That's what `offsetof` is for. – StoryTeller - Unslander Monica Oct 12 '17 at 14:36
  • This code is very confused. Even the parts that you say work don't actually compile. `Base Container::* ptr` is a nonsensical type name and it's impossible to figure out what you really mean. And in the code where you're asking about a compiler error, you're trying to take the address of something that doesn't even have an address. – Omnifarious Oct 12 '17 at 14:43
  • 1
    From your example `&Container::f2` cant access that anyway `f2` is private in the class - default access of a class, private. – Samer Tufail Oct 12 '17 at 14:45
  • I think you need a rethink about the design – Ed Heal Oct 12 '17 at 17:01
  • This would be much easier if you describe what you are trying to accomplish. – Beached Oct 12 '17 at 17:04
  • Container has a lot of Derived* members. Each has unique Base::type value. I want to have array of offsets to Derived objects to their Base parts. I have implemented it by offsetof-like logic (unfortunately I can't use offsetof), but I don't like it. May be better way to use pointer-to-member feature, but looks like it requires to define pointer-to-member of Derived class directly. I just wonder if someone knows how to use Base class here or know that it is impossible. – Vadim Kobyzev Oct 12 '17 at 17:23

1 Answers1

0

It's very likely you're looking for offset of and all related staff How to calculate offset of a class member at compile time?

Yury Schkatula
  • 5,291
  • 2
  • 18
  • 42