5

Can anyone tell me why this doesn't compile:

struct A { }; struct B : public A { }; int main() { B b; A* a = &b; B* &b1 = static_cast<B*&>(a); return 0; } 

Now, if you replace the static cast with:

B* b1 = static_cast<B*>(a); 

then it does compile.

Edit: It is obvious that the compiler treats A* and B* as independent types, otherwise this would work. The question is more about why is that desirable?

5
  • 2
    a is not a reference to pointers its a pointer. Commented Jan 17, 2013 at 15:45
  • @MrLister B*& is a reference to a pointer to B. Commented Jan 17, 2013 at 15:47
  • FYI, dynamic_cast would be more safer Commented Jan 17, 2013 at 15:54
  • @user814628 Only if you do not know (because of program logic) that the cast is valid, and using dynamic_cast forces the compiler to embed runtime type information into that class hierarchy. Combine this with the relatively slow operation of dynamic_cast and it's a solution which you don't want to use unless it's necessary. Commented Jan 17, 2013 at 16:03
  • 3
    @user814628 dynamic_cast would not be legal here. Commented Jan 17, 2013 at 16:04

4 Answers 4

7

B is derived from A, but B* isn't derived from A*. A pointer to a B is not a pointer to an A, it can only be converted to one. But the types remain distinct (and the conversion can, and often will, change the value of the pointer). A B*& can only refer to a B*, not to any other pointer type.

Sign up to request clarification or add additional context in comments.

Comments

3

non-constant lvalue reference (B*&) cannot bind to a unrelated type (A*).

Comments

0

Handling of references is something the compiler does for you, there should be no need to cast to reference.

If we refactor the code to:

B b; A* a = &b; B* b_ptr = static_cast<B*>(a); B*& p1 = b_ptr; 

It will compile.

1 Comment

I agree (see my post), but this doesn't do the same. For example, changing the pointee in p1 doesn't change the pointee in a.
-1

You are trying to cast an A* to a B*. This is the wrong way around and not very useful. You probably want to store a pointer to derived in a pointer to base, which is useful and doesn't even need a cast.

I suppose a dynamic_cast might work here, but the result is implementation defined if I'm not mistaken.

2 Comments

You cannot use dynamic_cast to convert a A* to a B*&. It's not legal, and the code won't compile.
Casting from A* to B* is the only direction in which static_cast make sense. In the other direction, there is nothing to be done.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.