c++ - Covariant clone function misunderstanding -
this question related recent 1 polymorphism not working function return values of same data type (base , inherited class)
consider code:
#include <iostream> #include <typeinfo> class base { public: virtual base * clone() { base * bp = new base ; return bp ; } }; class derived: public base { public: derived * clone() override { derived * dp = new derived ; return dp ; } }; int main() { base * bp = new derived; auto funky = bp->clone(); std::cout << typeid(funky).name() << std::endl; }
the output p4base
(i.e. pointer-to-base). why this? bp->clone()
should invoke covariant virtual derived* derived::clone
via base*
pointer, type of bp->clone()
should derived*
, not base*
.
the declaration
auto funky = bp->clone();
is equivalent to
base* funky = bp->clone();
since base::clone
returns base*
.
checking type of pointer yields base*
.
checking type of pointee different matter, when base
type polymorphic. , in presented code base
polymorphic because clone
virtual. understand more of functionality, check type of pointee instead of type of pointer.
Comments
Post a Comment