Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing members of class after casting pointer in C++

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?

like image 291
Nguyen Ngoc Minh Avatar asked Mar 16 '23 20:03

Nguyen Ngoc Minh


2 Answers

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.

like image 156
Lightness Races in Orbit Avatar answered Mar 18 '23 10:03

Lightness Races in Orbit


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)
like image 45
duong_dajgja Avatar answered Mar 18 '23 10:03

duong_dajgja