由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
Programming版 - c++ dynamic cast
相关主题
An interesting C++ compile errorC++ 的 问题
A C++ compiler related interview questionC++ virtual function 定义在 derived class 会怎么样?
C++小插曲Help! Virtual Destructor
问一下这个cast在java里是怎么work的急问:compile and build dependency
template 类的继承问题compiler created methods
C++ online Test 2题Forward declaration with unique_ptr
关于Makefile的一个问题pointer to base class = new derived, what will happend??
a question about CAST我这个C++程序有没有什么问题啊?请指点。。。谢谢。。。
相关话题的讨论汇总
话题: base话题: derived话题: pb1话题: dynamic话题: cast
进入Programming版参与讨论
1 (共1页)
r**u
发帖数: 1567
1
Asked during interview.
class Base {
int a;
};
class Derived : public Base {
int b;
};
int main() {
Derived *pD;
Base *pB = new Base();
Base *pB1 = pB;
pD = dynamic_cast(pB1); // <<-- This will give compilation
error.
}
Question is how does the compiler know that what pB1 points to is an object
of Base class not an object of Derived.
t****t
发帖数: 6806
2
to use dynamic_cast, you need at least one virtual members. if you don't
have virtual member, make dtor virtual is a good choice.
and you forgot the ().

【在 r**u 的大作中提到】
: Asked during interview.
: class Base {
: int a;
: };
: class Derived : public Base {
: int b;
: };
: int main() {
: Derived *pD;
: Base *pB = new Base();

S**I
发帖数: 15689
3
Compiler does not need to know: pB1's type is pointer to Base and Base is
not polymorphic (no virtual member function), dynamic cast is not allowed in
this case. Even if pB1 points to an object of class Derived, compiler will
still report error.

【在 r**u 的大作中提到】
: Asked during interview.
: class Base {
: int a;
: };
: class Derived : public Base {
: int b;
: };
: int main() {
: Derived *pD;
: Base *pB = new Base();

r**u
发帖数: 1567
4
I understand now. Thanks guys.

in
will

【在 S**I 的大作中提到】
: Compiler does not need to know: pB1's type is pointer to Base and Base is
: not polymorphic (no virtual member function), dynamic cast is not allowed in
: this case. Even if pB1 points to an object of class Derived, compiler will
: still report error.

1 (共1页)
进入Programming版参与讨论
相关主题
我这个C++程序有没有什么问题啊?请指点。。。谢谢。。。template 类的继承问题
C arrayC++ online Test 2题
请问c++为什么会编译失败?关于Makefile的一个问题
dynamic_cast operator in C++a question about CAST
An interesting C++ compile errorC++ 的 问题
A C++ compiler related interview questionC++ virtual function 定义在 derived class 会怎么样?
C++小插曲Help! Virtual Destructor
问一下这个cast在java里是怎么work的急问:compile and build dependency
相关话题的讨论汇总
话题: base话题: derived话题: pb1话题: dynamic话题: cast