开发者

Virtual Interface Dtor && Dynamic_Cast

开发者 https://www.devze.com 2023-02-06 03:47 出处:网络
I\'m trying to downcast from an interface to a derived class but my virtual dtor kills it? class IFOO {

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消