3

Below you will see 3 classes. My question is why can I use override on the getArea() of the FunnySquare Class, even though it is not tagged as virtual in the Square Class.

My assumption is that an overridden pure virtual function is virtual even though it is not specified, but I am not sure that is true and could not find any references to confirm.

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

class Square : public Shape {
  private:
  float length;

  public:
  Square(float len){
    length = len;
  }
  float getArea() override {
    return length * length; 
  }

  void sayHi() {cout << "hell0" << endl;}
};

class FunnySquare : public Square {
  public:
  FunnySquare(float len) : Square(len) {}
  void tellJoke() {std::cout << "I gave you the wrong area haha" << endl;} 
  
  float getArea() override {
    return 2.0;
  }
};
Max Dolensky
  • 107
  • 7

1 Answers1

2

Yes, both Square::getArea and FunnySquare::getArea are virtual too.

(emphasis mine)

Then this function in the class Derived is also virtual (whether or not the keyword virtual is used in its declaration) and overrides Base::vf (whether or not the word override is used in its declaration).

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • 1
    Which, btw. is one of the many things I *HATE* about C++. Nothing in the the source code should ever be "implicit". If a function is "virtual", the language should *require* you to say "virtual". If a variable is an "object", you should always specify "()" when you construct an instance. And don't get me started on how C++11 hijacked the keyword "auto"... – paulsm4 Sep 03 '21 at 03:10