0

I have read somewhere that if you dynamic_cast a void* you get the start of the address of the object ?
I have no clue about this. How is this possible.?
Can someone help me on this

2
Contributors
1
Reply
2
Views
10 Years
Discussion Span
Last Post by vijayan121
0

you cannot apply a dynamic_cast on a void* to get a non void pointer.
except in a trivial case, in dynamic_cast<T>(v), v should be a pointer to or an lvalue of a polymorphic type.
if T is a (cv qualified) void* , and v is a pointer to a polymorphic type, the result is a (cv qualified) void* pointer which points to the 'most derived object' pointed to by v.
here is an example:

#include <typeinfo>
#include <iostream>
using std::cout ;

struct A { virtual ~A() {} int a ; } ;
struct B : virtual A { int b ; } ; struct C : virtual A { int c ; } ;
struct D : virtual A, virtual B, virtual C
{
   D() { cout << "D::constructor - " ; foo() ; }
   ~D() { cout << "D::destructor - " ; foo() ; }
   void foo() { cout << dynamic_cast<void*>(this) << '\n' ; }
   int d ;
} ;
struct E : virtual A, virtual B, virtual C, virtual D { int e ; } ;

int main()
{
  E object ;
  E* pe = &object ;
  D* pd = pe ;
  C* pc = pe ;
  B* pb = pd ;
  A* pa = pc ;
  void* pv = &object ;

  cout << pv << '\n'
       << dynamic_cast<void*>(pa) << '\t' << pa << '\n'
       << dynamic_cast<void*>(pb) << '\t' << pb << '\n'
       << dynamic_cast<void*>(pc) << '\t' << pc << '\n'
       << dynamic_cast<void*>(pd) << '\t' << pd << '\n'
       << dynamic_cast<void*>(pe) << '\t' << pe << '\n' ;
  pe->foo() ; pd->foo() ;
}

>g++ -std=c++98 -Wall dyn_cast.cpp && ./a.out
D::constructor - 0xbfbfe990
0xbfbfe970
0xbfbfe970 0xbfbfe978
0xbfbfe970 0xbfbfe980
0xbfbfe970 0xbfbfe988
0xbfbfe970 0xbfbfe990
0xbfbfe970 0xbfbfe970
0xbfbfe970
0xbfbfe970
D::destructor - 0xbfbfe990

note the behaviour during construction/destruction of a base class.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.