5

What is the output of the following c++ code ?

#include<iostream> 
using namespace std;
class IndiaBix
{
    int x, y; 
    public:
    IndiaBix(int xx)
    {
        x = ++xx;
    } 
    ~IndiaBix()
    {
        cout<< x - 1 << " ";
    }
    void Display()
    {
        cout<< --x + 1 << " ";
    } 
};
int main()
{
    IndiaBix objBix(5);
    objBix.Display();
    int *p = (int*) &objBix;
    *p = 40;
    objBix.Display();
    return 0; 
}

I did n't understand the following line ::

 int *p = (int*) &objBix;//Explicit type cast of a class object to integer pointer type
3
  • @Andrey: I was about to ask the same, but looking at ecatmur's answer I can see this being a valid question. The muddy waters between UD and OK are a little hard to test with "just running it and see". Commented Aug 23, 2012 at 13:43
  • @honk: The 1st OP's question is "What is the output" Commented Aug 23, 2012 at 13:45
  • 1
    It's funny how people use these weird features, and then go on to complain C++ is a minefield... Commented Aug 23, 2012 at 14:04

1 Answer 1

12

It is possible to cast an object pointer (of a standard-layout type) to a pointer to its first member. This is because it is guaranteed that the first member of a standard-layout object has the same address as the overall object:

9.2 Class members [class.mem]

20 - A pointer to a standard-layout struct object, suitably converted using a reinterpret_cast, points to its initial member (or if that member is a bit-field, then to the unit in which it resides) and vice versa.

Thus int *p = (int*) &objBix; is a pointer to objBix.x, since objBix is standard-layout; both its data members x and y are private, and the class has no virtual methods or base classes.

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

6 Comments

Would it be advised to use size_t if one were needing to do this?
Beware: this is guaranteed only for standard layout types. Add a virtual function and you will be in undefined behavior land.
Only if the type is standard-layout.
@Aesthete I don't see how size_t is relevant.
This violates class visibilty too. x and y are both private.
|

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.