Reputation: 4001
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?
Circle::create()
does override - no compiler error.Upvotes: 0
Views: 91
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