2

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?

blurb
  • 600
  • 4
  • 20

2 Answers2

4

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

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • I'm thinking it's best practice to make that clear in all derived classes by declaring all inherited virtual functions virtual? – blurb Nov 27 '18 at 05:35
  • 3
    @briansrls better practice is declaring overriding functions `override` (which then makes `virtual` rather redundant). – Jesper Juhl Nov 27 '18 at 05:50
  • 2
    In other words it’s “virtual all the way down” :-) – Teivaz Nov 27 '18 at 07:49
4

You don't need to have a pure virtual function to get polymorphic behavior. Normal virtual function can also accomplish it.

Yes, specifying a function as virtual in a class means that it remains virtual in all the classes derived from it.

From C++11 onwards, there is also the override specifier:
In a member function declaration or definition, override ensures that the function is virtual and is overriding a virtual function from a base class.

P.W
  • 26,289
  • 6
  • 39
  • 76
  • Okay, I will include override in derived class overridden virtual functions. Would including the keyword "virtual" and "override" be redundant? – blurb Nov 27 '18 at 05:41
  • 2
    Yes. See this question and answers for some more info. https://stackoverflow.com/questions/43466863/isnt-virtual-keyword-redundant-when-override-or-final-specifiers-are-used – P.W Nov 27 '18 at 05:47