0
#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 ?

1
  • That's undefined behavior. The C++ standard doesn't specify what happens when you cast a pointer to an unrelated type and dereference it. The position of the elements in a class is also not specified. Your compiler can add padding. Commented May 8, 2020 at 14:13

1 Answer 1

1

When you do this:

void * p = &der;
int i = *(int*)p;

you are (indirectly) casting a derived pointer to an int pointer. This invokes undefined behaviour, and the program could print anything. It can even print different results when you run it a second time.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.