c++ - Why is typeid behaving differently for references and pointers? -
this question has answer here:
- typeid polymorphic types 1 answer
- typeid polymorphic pointers? 2 answers
basically wondering why typeid not return typeinfo of derived type if given pointer derived type.
example:
if having:
class base { public: virtual void foo() { std::cout << "this base speaking" << std::endl; } }; class derived : public base { public: void foo() override { std::cout << "this derived speaking" << std::endl; } }; the following:
derived obj; base& ref = obj; base* ptr = &obj; std::cout << typeid(obj).name() << std::endl; std::cout << typeid(ref).name() << std::endl; std::cout << typeid(ptr).name() << std::endl; would result in:
7derived 7derived p4base while this:
obj.foo(); ref.foo(); ptr->foo(); would result in:
this derived speaking derived speaking derived speaking my guess base* type in itself, namely pointer base not polymorphic , hence statically determined. reason why call foo results in derived version because of dereferencing (->). if i'm right, still find confusing, since object pointed ptr derived.
Comments
Post a Comment