• Advertisement
Sign in to follow this  

Dynamic_cast in constructor. Please

This topic is 3395 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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!!! :)

Share this post


Link to post
Share on other sites
Advertisement
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.

Share this post


Link to post
Share on other sites
Also, CRTP.

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

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement