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.