Search code examples
c++inheritancevirtual

C++ Pure virtual derived function


I'm learning about object oriented C++ and had a question about virtual/pure virtual and multi-level inheritance.

Lets say I have simple code like this:

class Shape
{
    virtual int getWidth() = 0;
};
class Rectangle: public Shape
{
private:
    int length, width;
public:
    Rectangle(_length, _width) { length = _length; width = _width }
    int getWidth() { return width }
};
class Square: public Rectangle
{
private:
    int length;
public:
    Square(int _length):Rectangle(_length, _length) { length = _length };
    int getWidth() { return length+1 }; //arbitarily add 1 to distinguish
};

int main()
{
    Rectangle* r = new Square(5);
    std::cout << r->getWidth << std::endl;  //prints 6 instead of 5?  It's as if rectangles getWidth is virtual
}

My understanding is that polymorphism will use the function of the "Base" class unless getWidth is specified as virtual. By this I mean that the final call of r->getArea should be using the Rectangle's getArea instead of Square's getArea.

In this case, I notice if I remove the pure virtual declaration in Shape, we get the behavior I just described. Does having a pure virtual function in a base class automatically make all definitions of that function virtual?


Solution

  • virtual is inherited. If you make a parent function virtual then it will keep on being virtual in all child-classes.