Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit type casting of object to int *

Tags:

c++

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
like image 943
Ritesh Kumar Gupta Avatar asked Aug 23 '12 13:08

Ritesh Kumar Gupta


People also ask

What is explicit type casting?

Explicit type conversion, also called type casting, is a type conversion which is explicitly defined within a program (instead of being done automatically according to the rules of the language for implicit type conversion). It is defined by the user in the program.

How do you turn an object into an int?

If your object is a String , then you can use the Integer. valueOf() method to convert it into a simple int : int i = Integer. valueOf((String) object);

What is explicit cast in C++?

C++ Explicit Conversion. When the user manually changes data from one type to another, this is known as explicit conversion. This type of conversion is also known as type casting.

What does casting to an int do?

Casting in python is therefore done using constructor functions: int() - constructs an integer number from an integer literal, a float literal (by removing all decimals), or a string literal (providing the string represents a whole number)


1 Answers

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:

c++11

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.

like image 108
ecatmur Avatar answered Oct 05 '22 23:10

ecatmur