Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static casting to incorrect type

Tags:

c++

I Realised that this method is particularly useful when debugging code when I Don't want to change/build an an external library.

Am yet to burn my hands with this or is this safe atleast for debugging?

http://ideone.com/i9jBN8

#include <iostream>
using namespace std;

class A
{
public:
    A(int lx):x(lx){};
protected:
    int x;
};

class B : public A
{
public: 

    void print(){std::cout << x << endl;}
};

int main() {
    A *a = new A(22);
    B *b = static_cast<B*>(a);
    b->print();
}

Edit: what if use I use reinterpret_cast instead of static_cast and make sure that B doesn't have any virtual methods, wouldn't the memory of A and B match and it wont be an UB right?

like image 808
tejas Avatar asked Oct 15 '25 14:10

tejas


1 Answers

Your code has undefined behavior, but since it's quite simple you can probably convince yourself whether it'll work on your implementation by examining the intermediate assembly code or the disassembled binary.

Chances are good that it will work in practice, especially for simple classes. The main fear with these kinds of "it looks like it ought to work even though it's UB" situations, is that the optimizer will make some very clever deduction based on an assumption that it's entitled to make, but which isn't true of your UB code. So turning off all optimization gives you a better chance of seeing (dis)assembly that (a) does what you intended and (b) you can make sense of.

For this example at least, you can access the value of x for debugging purposes without undefined behavior and without modifying the class A, by taking a copy:

class B : public A
{
public: 
    B(const A&a) : A(a) {}

    void print(){std::cout << x << endl;}
};

int main() {
    A *a = new A(22);
    static_cast<B>(*a).print();
}
like image 144
Steve Jessop Avatar answered Oct 17 '25 02:10

Steve Jessop



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!