#include <iostream>
using namespace std;
class temp {
int a = 10;
};
class derived : temp {
int b = 20;
};
int main()
{
derived der;
void * p = &der;
cout<<"First element in der is : "<<*(int*)p<<endl;
cout<<"(int*)p :"<<(int*)p<<endl;
p += sizeof(int); //Way -1
//p = (int*)p + sizeof(int); //Way-2
cout<<"Second element in der is : "<<*(int*)p<<endl;
cout<<"(int*)p :"<<(int*)p<<endl;
return 0;
}
If I execute the above code, I get below output :
First element in der is : 10
(int*)p :0x7ffe9f05a928
Second element in der is : 20
(int*)p :0x7ffe9f05a92c
Where as if I comment the line of code in (Way-1) and un-comment line for (Way-2) I get below output :
First element in der is : 10
(int*)p :0x7ffc10e6de18
Second element in der is : 0
(int*)p :0x7ffc10e6de28
What is going wrong in second attempt ? Why pointer arithmetic results are different here ?