I have written a few lines of code which I think should not compile. I am calling a method of a derived class on a static_cast-ed pointer to object of base class as follows:
class B {};
class D: public B
{
public:
void bar() { printf("%d\n", m_i); }
private:
int m_i;
};
int main()
{
B b;
D* d = static_c开发者_高级运维ast<D*>(&b);
d->bar();
return 0;
}
The value printed is obviously junk but should this even compile? How does gcc
manage to do that?
gcc
can't guarantee that it's incorrect, except in enough of a minority of cases that it really isn't worth checking. When you use static_cast
, then you are promising the compiler that you know wtf you're doing.
There are two kinds of casts here. static_cast
, which is, you are telling the compiler that pointer to a base IS a pointer to derived, and shut up and get on with it. dynamic_cast
, which is, you are asking the compiler to check if that pointer to base is indeed a pointer to derived. You used static_cast
, so the compiler shut up and did as you said.
Edit: John accurately pointed out that there are no virtual functions in your inheritance hierarchy, for which you should be fired from C++, and dynamic_cast
is only valid for virtual functions.
Using the static_cast<> you told the compiler "I know what I am doing, that B* is actually D*, shut up and just do what I say."
精彩评论