Dynamic_cast in constructor. Please
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!!! :)
During Base::Base(), derived classes aren't constructed yet. It would be unsafe to access their members or member functions.
Consider:
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.
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.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement