in following code, can assign return of d::clone() pointer b, not pointer d. is possible return actual polymorphic type call of base pointer?
struct b { virtual b * clone() { return this; } }; struct d : b { d * clone() { std::cout << std::is_same<decltype(this), d *>::value << std::endl; return this; } }; int main() { b * b = new d(); b * bb = b->clone(); // prints "1" std::cout << std::is_same<decltype(b->clone()), d *>::value << std::endl; // prints "0" d * d = b->clone(); // error: invalid conversion b * d * (gcc 5.1) }
no. call of clone() on base b class of d return d* cast b*.
you can reverse doing static_cast<d*> if absolutely certain, or dynamic_cast<d*> if not certain. if certain, should make variable b d*.
in c++, should encode know state of program @ compile time regardless of run time situation types. storing d* b* b, telling compiler not "know" data being pointed "is d". instead, saying "the code using b*b should valid pointer-to-b. d* d = b->clone(); not guaranteed valid every pointer-to-b.
Comments
Post a Comment