galah92
galah92

Reputation: 4001

override method not called from pointer to base class

class Shape {
public:
    virtual Shape* create() { return new Shape(); }
    virtual ~Shape() {}
};

class Circle : public Shape {
public:
    virtual Circle* create() override { return new Circle(); }
};

int main() {
    Shape *sp = new Circle();
    Circle *cr = sp->create(); // invalid conversion from ‘Shape*’ to ‘Circle*’
    delete sp;
}

Why is that, shouldn't Circle::create() get called?

Upvotes: 0

Views: 91

Answers (1)

eneski
eneski

Reputation: 1675

Method create() is defined in base class. The method signatures must be the same in order to override a method in derived class. But the thing here is that return type is not included to method signatures. This is why you are seeing the return type of call sp->create() is still in type Shape *.

Upvotes: 3

Related Questions