Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading