c++ - dynamic_cast "this" to derived type: when is it legal? -


here code doesn't work, since downcasting "this" in constructor illegal:

#include <cassert>  class { protected:         virtual ~a() {} public:         a(); };  class b : public { };  a::a() {         assert(dynamic_cast<b*>(this)); }  int main(void) {         b b;         return 0; } 

as expected, when compiled g++, assertion fails.

here code that, however, works (with g++ 4.7, @ least, haven't tried other compilers):

#include <cassert>  class { protected:         virtual ~a() {} public:         a() {}         void f(); };  class b : public { public:         b() {                 f();         } };  void a::f() {         assert(dynamic_cast<b*>(this)); }  int main(void) {         b b;         return 0; } 

my question is: second code "legal", i.e. can expect compiler work way?

my intuition since f() called body of b's constructor, "b" formed instance of type b, makes code legal. yet, i'm still kind of dynamic_casting "this" constructor...

(note question not whether practice or not, if it's legal).

yes, second example defined, , cast succeed. during constructor of b, dynamic type of object b, cast b* succeed.

in first example, say, in constructor of a dynamic type a, cast b* fail.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -