Sign in to follow this  
Nene

Dynamic_cast in constructor. Please

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
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this