I am a newbie in C++. Can anyone tell me why the 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* a = new A();
((B*)a)->sayHello();
a->sayGoodbye();
return 0;
}
Output:
create a
hello
goodbye
What I wonder is why can the a access B::sayHello just by casting like that? Can it access every public members of any class by that way?
Yes, you can.
But, no, you can't.
When you use a C-style cast like that, you are promising to the computer that you know what you're doing, and that the cast is valid. When it is valid, you're fine. When it's not, it's your fault.
In this case, it's not, and it's your fault.
Now, you can ask why it "runs well", but that's incidental: that's pure chance. Once the program is compiled, it's only going to crash or murder your step-children if you literally access invalid memory. In this particular case, you're not accessing invalid memory.
Doesn't mean you're right, though.
Don't do this.
This is not an answer to your question, however it can give you more knowledge and options when working with pointer casting:
You can see several casting techniques as follows:
static_cast
dynamic_cast
const_cast
reinterpret_cast
C-style cast (type)value
Function-style cast type(value)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With