2

I know since reading this question that a dynamic_cast<void*> is the best way to check an object pointer's true identity and ensure any base pointers will also compare eequally to the most derived (after the cast).

What I'm not sure about is that this cast gives defined and useful results in the non-polymorphic case. If not, can I work around this or is this a hopeless situation?

What I'm asking is if this is well-defined:

class A {};
class B : public A {};

int main()
{
  A a;
  B b;
  A* base_ptr = &b;

  void* pointer = dynamic_cast<void*>(&a); // is this value well-defined?

  if(dynamic_cast<void*>(&b) == dynamic_cast<void*>(base_ptr))
    std::cout << "Is this undefined or not?";
}
Community
  • 1
  • 1
rubenvb
  • 74,642
  • 33
  • 187
  • 332

1 Answers1

3

This code doesn't compile and therefore doesn't produce any value, well-defined or otherwise. It runs afoul of

[expr.dynamic.cast]/6 Otherwise, v shall be a pointer to or a glvalue of a polymorphic type.

Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85