C++ Const Method Override – Why Doesn’t a Const Method Override a Non-Const Method in C++?

c++

Consider this simple program:

class Shape
{
public:
    virtual double getArea() = 0;

};

class Rectangle : public Shape
{
    int width;
    int height;

public:
    Rectangle( int w , int h ) :width(w) , height(h) {}

    double getArea() const
    {
        return width * height;
    }
};


int main() {

    Rectangle* r = new Rectangle(4,2);
}

Trying to compile this problem gives me:

 'Rectangle' : cannot instantiate abstract class

Why is this not allowed in C++ when covariant return types are? Of course I can fix the program by making Rectangle::getArea to be a non-const function but I am curious as to why the language designers decided otherwise.

EDIT

Lots of people have mentioned in their answers how the signature is different. But so is

class Shape
{
public:
    virtual BaseArea* getArea() = 0;

};

class Rectangle : public Shape
{
public:
    virtual RectangleArea* getArea();
};

but C++ goes out of its way to allow it, when C# doesn't.

C++ supports covariant return types because if I expect an interface to return a BaseArea* and an implemention returns a RectangleArea*, it is ok as long as RectangleArea derives from BaseArea because my contract is met.

On the same lines, isn't an implementation that provides a non-mutating function satisfying an interface that only asks for a mutating function?

Best Answer

What would happen in this case:

struct base
{
    virtual void foo(); // May implement copy-on write
    virtual void foo() const;
};

struct derived : base
{
    // Only specialize the const version, the non const
    // default suits me well. How would I specify that I don't
    // want the non-const version to be overriden ?
    void foo() const;
};
Related Question