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
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.
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);
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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With