I'm trying to understand a polymorphism but I don't understand why we need runtime polymorphism if static polymorphism works fine for calling members of a class.
Like, suppose this was a problem.
#include <bits/stdc++.h>
using namespace std;
class base{
public:
virtual void fun(){
cout<<"base called"<<endl;
}
};
class derived:public base{
public:
void fun(){
cout<<"derived called"<<endl;
}
};
int main() {
base b,*b1;
derived d;
b1 = &d;
b1->fun();
// b.fun();
// d.fun();
}
suppose this was my code and I want to access the function of derived or base class and I was able to do it by simply creating an object of that class so if there is no problem then why we try to call the object using references (runtime polymorphism). Can someone explain the actual need for runtime polymorphism or if it is possible can you explain it by using any real-life scenarios??
void f(base* b) { b->fun(); }
. Which function does it call? – Sussi