Covariant Return Types of Objects

Viewed 46

The following code.

#include <iostream>
using namespace std;
#include <stdio.h>


class mother {
    public:
     virtual mother* display() {};
};

class daughter : public mother
{
    public:
    daughter* display()
    {
        daughter *d1 = new daughter();
        std::cout << "This is the daughter" << std::endl;
        return d1;
    }

    void signature()
    {
        cout<<"I'm the sign"<<endl;
    }
};

int main() {
    //code
    mother *w = new daughter();
    daughter *w2 = w->display();
    w2->signature();
    return 0;
}

Returns an error that daughter w2 cannot be assigned from the return value of w->display(). But from what I know, display is a virtual function. So w->display() should call the daughter variation of the display function, which has a return type of daughter. Then exactly why isn't this working and what could be changed?

1 Answers

This is the correct behavior, the code has a mistake: mother::display returns a pointer to mother, you are "driving" display from a pointer to mother, syntactically. Then you are asking to convert a pointer to mother to daughter, which is a "downcast", not all mothers are daughters in your hierarchy, so, you have to use an explicit cast. This is the syntax.

You "know" the real object is of type daughter, so, it will return a type of mother that is a daughter, but this is not said in the syntax. The compiler will not go and practically execute your source code to compile it, that is not how it works.

You can do this:

daughter *w2 = static_cast<daughter *>(w->display());

or

daughter *w2 = dynamic_cast<daughter *>(w->display());

Use static_cast only if you can prove the object is indeed of the type you say it is, dynamic_cast (and test) otherwise. static_cast has no penalty, the compiler "trusts" you.

Related