I'm trying to downcast from an interface to a derived class but my virtual dtor kills it?
class IFOO
{
public:
virtual ~IFOO(){};
virtual size_t index() PURE;
};
class FOO : public IFOO
{
public:
FOO() : size(5){};
~FOO(){};
virtual size_t index(){ return index; };
size_t index;
};
int main() {
IFOO* A = &FOO();
FOO* 开发者_JAVA技巧B = dynamic_cast< FOO* >( A );
return 0;
}
Why is this so?
You are taking the address of a temporary in the line
IFOO* A = &FOO();
It should be
IFOO* A = new FOO();
I guess the code works if you remove the dtor from your interface, because in that case it will not be called, and you enter the realm of undefined behavior, in which anything is possible, even bad code working as expected.
Also, i would recommend that you do not write your class names in all capitals, because that is usually the convention for macros (unless your class names are macros, but surely, that cannot be). Also, don't use a macro (PURE
) to make functions pure virtuals, this confusing 95% of the people that might have to read your code.
精彩评论