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.
|