c++ cli - Accessing members of class after casting pointer in C++ -
i newbie in c++. can tell me why following source code runs well?
#include <iostream> using namespace std; class a{ public: a(){ cout << "create a" << endl; } void saygoodbye() { cout << "goodbye" << endl; } }; class b{ public: b() { cout << "create b" << endl; } void sayhello() { cout << "hello" << endl; } }; int main(array<system::string ^> ^args) { a* = new a(); ((b*)a)->sayhello(); a->saygoodbye(); return 0; }
output:
create hello goodbye
what wonder why can access b::sayhello casting that? can access every public members of class way?
yes, can.
but, no, can't.
when use c-style cast that, promising computer know you're doing, , cast valid. when is valid, you're fine. when it's not, it's your fault.
in case, it's not, , it's fault.
now, can ask why "runs well", that's incidental: that's pure chance. once program compiled, it's going crash or murder step-children if literally access invalid memory. in particular case, you're not accessing invalid memory.
doesn't mean you're right, though.
don't this.
Comments
Post a Comment