Dynamic_cast in constructor. Please

Started by
3 comments, last by Antheus 15 years, 5 months ago
Hi everyone, I have a problem with the following dynamic_cast (it returns 0): template<class T> class Base { public: Base(){ T* t = dynamic_cast<T*>(this); } virtual ~Base(){} }; class Derived : public Base<Derived>{ public: Derived():Base(){} void g(){} }; int main() { Derived d; } Any suggestion? Thanks a lot!!! :)
Advertisement
The object is not yet a Derived. explanation
During Base::Base(), derived classes aren't constructed yet. It would be unsafe to access their members or member functions.

Consider:
template<class T>class Base{    Base()    {         T *self = dynamic_cast<T*>(this);         self->frobnicate();    }}class Derived : public Base<Derived>{    void frobnicate()    {        // manipulate member.    }    std::string member;};

If the dynamic_cast returned a pointer, and we call frobnicate on it, the code would probably crash at run time. That is a best case scenario - it could also silently corrupt unrelated memory, creating a debugging nightmare.
You're right, thanks. I didn't figure it out :P
Also, CRTP.

Note that template specialization is resolved at compile-time. But it is still not safe to use Derived's functions in constructor.

This topic is closed to new replies.

Advertisement