An overridden virtual function in a derived class can be called in polymorphic manner through the base class reference or pointer. But, can the derived class have a more restrictive access specifier on an overridden virtual function than the base class?
In our example code the class Rectangle overrides its base class Shape's virtual function area:
class Shape {
public:
virtual int area() {
return 0;
};
};
class Rectangle : public Shape {
public:
Rectangle(int w, int l)
:width(w),length(l){}
private:
int area() override { // <--- It's private
return width*length;
}
int width{0}, length{0};
};
Note that Rectangle::area is declared private, whereas Shape::area is public. The Rectangle is instantiated somewhere and the function area is called on the base class, Shape, pointer as follows:
Shape* ptrShape = new Rectangle(10,20);
std::cout << ptrShape->area() << "\n";
What is the outcome of above code? Select below: