I am learning to use static_cast and wrote the following code, but the garbled output confuses me. What could be causing the garbled output? Code:
#include <iostream>
using namespace std;
class Base {
public:
char x;
};
class Derived : public Base {
public:
char y;
};
class Foo {
public:
char x;
};
class Derived2th : public Derived, public Foo {
public:
char z;
char j;
char k;
char l;
};
int main() {
int *p = new int(2);
Base a0;
Base a1;
Base a2;
Base* b = &a1;
// Foo* f = static_cast<Foo*>(b); // compile error
Derived2th* d = static_cast<Derived2th*>(b);
cout << d->y << endl;
d->y = 'p';
cout << "[address]a0:" << &a0 << endl;
cout << "[address]a1:" << &a1 << endl;
cout << "[address]a2:" << &a2 << endl;
cout << "[address]d->Base:x:" << &(d->Base::x) << endl;
cout << "[address]d->Foo:x:" << &(d->Foo::x) << endl;
cout << "[address]d->y:" << &(d->y) << endl;
return 0;
}
Output:
�
[address]a0:0x7ff7b058c148
[address]a1:0x7ff7b058c140
[address]a2:0x7ff7b058c138
[address]d->Base:x:`pX��
[address]d->Foo:x:X��
[address]d->y:pX��
To my understanding, no matter what address is printed, it should always be a number. So why is there garbled text appearing in the output?
Firstly, this is wrong:
Since
bis a pointer to an instance ofBase, any use ofdis Undefined behaviour (any decent static analyser will identify this problem). This is why you need to take great care withstatic_castandreinterpret_cast. Safer is to usedynamic_cast- but always remember to check whether the result is null (which it would be here, for the reason above).The string output from the
char*fields is becausestd::ostreamhas multiple overloads foroperator<<:operator<<(const void*)prints the value of the pointer.operator<<(const char*)prints a C-style (null-terminated) string beginning at the pointed-to location.