current position:Home>The pointer of the derived class shows why the value of the pointer data member converted to the base class has changed. Please explain

The pointer of the derived class shows why the value of the pointer data member converted to the base class has changed. Please explain

2022-02-02 12:55:12 CSDN Q & A

The original code where y be equal to 2f, The final result is 1.45f-45
#include
using namespace std;
struct Base1 { int x; };
struct Base2 { float y; };
struct Derived :Base1, Base2{ };
int main()
{
Derived* pd = new Derived;
pd->x = 1; pd->y = 2.0f;
void* pv = pd;
Base2* pb = static_cast<Base2*>(pv);
cout << pd->x << " " << pb->y << endl;
delete pb;
return 0;
}
And if implicit conversion is not a problem .
#include
using namespace std;
struct Base1 { int x; };
struct Base2 { float y; };
struct Derived :Base1, Base2{ };
int main()
{
Derived* pd = new Derived;
pd->x = 1; pd->y = 2.0f;
void* pv = pd;
Base2* pb = pd;
cout << pd->x << " " << pb->y << endl;
delete pb;
return 0;
}
do not know why

copyright notice
author[CSDN Q & A],Please bring the original link to reprint, thank you.
https://en.primo.wiki/2022/02/202202021255103218.html

Random recommended