Pointers to classes and reinterpret_cast<>()?

Hello, i'm new to C++, this website and programming in general i've been doing some pointer and reading up tutorials and watching vids anything i could get my hands on so would someone break this down to me why this code prints the following?

00000007
7

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
    #include <iostream>
    using std::cout;
    using std::cin;
    using std::endl;
    class Base {int special = 7; void foo() {}};

void basePtr(Base* base) {
	int** intPtr = reinterpret_cast<int**>(base);
	cout << *intPtr << endl;
	
}

void basePtr2(Base* base) {
	int* intPtr = reinterpret_cast<int*>(base);
	cout << *intPtr << endl;
}

int main()
{
	Base baseObj;
	basePtr(&baseObj);
	basePtr2(&baseObj);
    return 0;
}
Hello, i'm new to C++,

A good reason to stay away from reinterpret_cast.


would someone break this down to me why this code prints the following?

Because it does. This code has undefined behavior. It could print out anything.

It really doesn't though, i mean everytime i change the value of special and invoke basePtr() there are 7 0s followed by the value of special, a representation of 8 bits. It striked me as odd how a pointer to pointer variable handled it vs just a pointer which prints a plain 7.
Last edited on
It really doesn't though,

It really does. At least, according to the standard. I can see how you might think your anecdotal experience trumps the standard, though.


i mean everytime i change the value of special and invoke basePtr() there are 7 0s followed by the value of special, a representation of 8 bits. It striked me as odd how a pointer to pointer variable handled it vs just a pointer which prints a plain 7.

The difference with the zeros is the difference in how an output stream formats output for pointers and for ints.

You can see that behavior in the following code which has no undefined behavior:

1
2
3
4
5
6
7
#include <iostream>

int main()
{
    std::cout << (void*) 7 << '\n';
    std::cout << 7 << '\n';
}


And you can see that different implementations may result in different representations:
http://ideone.com/DGuZnt
Topic archived. No new replies allowed.