Search code examples
c++pointerspolymorphism

why dereference an polymorphism pointer will get the pointer's type rather than object's type?


I have this simple testing code:

class father{
    public:
        father()= default;
        virtual void func(){
            cout <<"father" << endl;
        }
};

class child:public father{
    public:
        child() = default;
        void func(){
            cout << "child" << endl;
        }
};

int main(){
    father* fptr = new child;
    auto s = *fptr; //why type of s will be father?
    (*fptr).func(); //child
    s.func(); //father
    return 0;
}

I don't know why type s will be father. If dereference a pointer will eliminate the polymorphism, why (*fptr).func();works fine?


Solution

  • Because fptr is a pointer to father then the deduced type of s will be father and with

    auto s = *fptr;
    

    you get a copy of the father part of the object.

    But in the expression (*fptr).func() the result of (*fptr) is a reference (more specifically an rvalue reference). Polymorphism works either through pointers, or through references.

    auto& s = *fptr;
    

    or

    auto&& s = *fptr;
    

    will both make your program work.