1

As a C++ beginner, I was going through a cpp program demonstrating function overriding with one base class and two derived classes and the output of this program was quite unexpected for me. Below is the code:

// Base class
class Shape {
   public:
      void get_Area() {   cout << "This is call to parent class area"<<endl;   }
};

// Derived class
class Square: public Shape {
   public: 
      void get_Area() {  cout << "Square area "<< endl;    }
};
// Derived class
class Rectangle: public Shape {
   public:
    void get_Area() {    cout << "Rectangle area";    }
};

int main(void) {
   Shape *s;
   Square sq; //making object of child class Square
   Rectangle rec; //making object of child class Rectangle

   s = &sq;
   s->get_Area();
   s= &rec;
   s->get_Area();
   return 0;
}

// Actual Output                              //Expected Output (according to me)
// This is call to parent class area          // Square area
// This is call to parent class area          // Rectangle area

According to my understanding, as the object of Square class is being pointed by 's', and then the method 'get_Area()' is called, then it was supposed to call 'get_Area()' method of 'Square' class and not the 'Shape' class, i.e, print "Square area" and not "This is call to parent class area". The same thing is going on with the Rectangle class. I think I am missing something few concepts here.

Siddhant
  • 626
  • 1
  • 7
  • 20
  • 1
    Yep, follow the duplicate link. Essentially the only way that `s` is going to call the `get_Area` from a derived class is for there to be something special about the object saying which version of the function to call. That's what virtual functions are for. – Tim Randall May 06 '21 at 20:06
  • @TimRandall yes, I understood now, and thank you. – Siddhant May 06 '21 at 20:08
  • 1
    FYI, C++11 introduced the [`override`](https://en.cppreference.com/w/cpp/language/override) specifier for exactly this kind of situation. Had `Square::get_Area()` and `Rectangle::get_Area()` been marked as `override` (eg: `void get_Area() override { ... }`), the compiler would have complained that `Shape::get_Area()` wasn't marked as `virtual`. – Remy Lebeau May 06 '21 at 20:17

0 Answers0