-
December 9th, 2011, 11:14 AM
#1
Reference to a pointer of another type
The minimum amount of code that reproduces the problem. I have a pointer of static type A, which points to a valid B.
I'd like to handle said pointer like a B, but not create a new pointer => I though of using a reference.
Code:
class A{};
class B : public A{};
int main()
{
A* pA = new B;
B*& pB1 = static_cast<B*>(pA); //error: invalid initialization of non-const reference of type 'B*&' from a temporary of type 'B*'
B*& pB2 = static_cast<B*&>(pA); //error: invalid static_cast from type 'A*' to type 'B*&'
}
I can understand why both of these examples don't compile, but how could I get it to work? I pretty sure what I'm trying to do is legal...
I'd use reinterpret_cast, but it wouldn't work if B actually had multiple inheritance...
Any help?
Is your question related to IO?
Read this C++ FAQ article at parashift by Marshall Cline. In particular points 1-6.
It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|