-2

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?

ConnellyM
  • 173
  • 7
  • 3
    *"To my understanding, no matter what address is printed, it should always be a number.*" - Nope. Overloads of `operator <<` accepting a pointer to char assume that it is a pointer to null-terminated string and print that string. – user7860670 Jul 07 '23 at 06:46
  • @user7860670 get it. thanks a lot. – ConnellyM Jul 07 '23 at 06:53

1 Answers1

2

Firstly, this is wrong:

    Derived2th* d = static_cast<Derived2th*>(b);

Since b is a pointer to an instance of Base, any use of d is Undefined behaviour (any decent static analyser will identify this problem). This is why you need to take great care with static_cast and reinterpret_cast. Safer is to use dynamic_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 because std::ostream has multiple overloads for operator<<:

  • 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.
Toby Speight
  • 27,591
  • 48
  • 66
  • 103