c++ - Difference between static and dynamic cast -
c++ - Difference between static and dynamic cast -
the class polymorphic. why both print same output?
class { public: virtual void p(){ cout << "a" << endl; } }; class b : public { public: void p()override{ cout << "b" << endl; } b(){ cout << "created b" << endl; s = "created b"; } string s; };
and main: variant 1:
a* = new b(); // created b b* b = static_cast<b*>(a); b->p(); b cout<<b->s<<endl; // created b
and variant 2:
a* = new b(); b* b = dynamic_cast<b*>(a); if (b){ b->p(); cout << b->s << endl; // prints same }
both of examples same thing, , that's fine. seek instead:
a* = new a();
in case, static_cast
"succeed" (though undefined behavior), whereas dynamic_cast
"fail" (by returning nullptr, check for).
your original examples don't show interesting because both succeed , valid casts. difference dynamic_cast lets observe invalid casts.
if want know how dynamic_cast
this, read rtti, run time type information. additional bookkeeping c++ in cases inspect type of object (it's of import , if utilize typeid()
).
c++ dynamic-cast static-cast
Comments
Post a Comment