static_cast from Derived* to void* to Base*

Posted by Roberto on Stack Overflow See other posts from Stack Overflow or by Roberto
Published on 2013-10-27T03:31:12Z Indexed on 2013/10/27 3:53 UTC
Read the original article Hit count: 104

Filed under:
|

I would like to cast a pointer to a member of a derived class to void* and from there to a pointer of the base class, like in the example below:

#include <iostream>

class Base
{
    public:
       void function1(){std::cout<<"1"<<std::endl;}
       virtual void function2()=0;
};

class Derived : public Base
{
    public:
       virtual void function2(){std::cout<<"2"<<std::endl;}
};

int main()
{
    Derived d;
    void ptr* = static_cast<void*>(&d);
    Base* baseptr=static_cast<Base*>(ptr);
    baseptr->function1();
    baseptr->function2(); 
}

This compiles and gives the desired result (prints 1 and 2 respectively), but is it guaranteed to work? The description of static_cast I found here: http://en.cppreference.com/w/cpp/language/static_cast only mentions conversion to void* and back to a pointer to the same class (point 10).

© Stack Overflow or respective owner

Related posts about c++

Related posts about static-cast