Why does this fail without static_cast?
Compiling f works, but compiling g fails with an error.
Why does this happen?
class A {
p开发者_如何学Pythonublic:
A() {}
};
class B : public A {
public:
B() {}
};
void f() {
A* a = new A();
B* b = static_cast<B*>(a);
}
void g() {
A* a = new A();
B* b = a;
}
A static_cast
forces a conversion that is potentially unsafe.
B* b = static_cast<B*>(a);
This would be valid if a
pointed to an A
object that actually was the base class sub-object of a B
object, however it doesn't. The cast forces the conversion.
B* b = a;
There is no cast here and there is (correctly) no implicit conversion allowed from base class pointer to derived class pointer. A pointer to a derived class can always be converted to a pointer to a base class because a derived class object always contains a base class sub-object but not every base class instance is a sub-object of a particular derived class type.
Well, yeah. Doing:
B* b = new A();
Is unsafe. You end up with a B pointer to an A object; you never construct the B portion of the object; your object is "sliced".
On the other hand...
A* a = new B();
...would be fine.
You are trying to convert a pointer from A* to B*. I am not sure what you are trying to achieve. But since B* is derived from A* and not the other way around this is not valid. Maybe you want to do something like this:
int main()
{
///The above code compiles while if I replace above two line in main with below assignment it gives error.
A *a=new A();
A * b=new B();
}
Yes, it does give an error if you want to assign a base class to a derived class pointer type. No, it doesn't give an error if you explicitly cast the pointer type, because in C++ you are allowed to shoot yourself in the foot if you so desire.
What exactly is baffling you, or what did you expect to achieve with your code?
A base class cannot be implicitly converted to a derived class. Just consider this
class A {
public: int x;
};
class B : public A {
public: int y;
};
B* b = new A; // assume it works, so 4 bytes is allocated and initialized.
b->y; // bam! accessing unallocated region.
精彩评论