int main()
{
Base*ptr=new Derived;
ptr->display();
return 0;
}
in the above polymorphism why is it called runtime polymorphism when i can say seeing the code itself that display() function in derived gets executed with ptr->display(),so how does it become runtime polymorphism when i could get decide at compile itself ??????????.....i am new to c++ please help
You're calling the function from a pointer to a Base, which could be pointing to any kind of Base, not just Derived. And so when you call methods from this pointer, it goes to the class of the pointer type (Base) then polymorphism at runtime sets up the correct actual function to be called.
A large scale C++ project could have hundres of classes. Consider the abstract factory pattern where a user of an object is given a base class pointer to something without knowing what the derived type actually is. Of course it is hard to understand the use when you are looking at such a simplistic example. Perform a web search on the aforementioned pattern, and look at some examples. Perhaps then you will understand. In many cases, the construction will occurr in a place that is far removed from where the user of the object makes a function call. The idea here is to minimize compile time dependencies by separating interface from the implementation. Factories build collections of similar objects, and return pointers to the base classes. Now you can code the user classes to the interfaces. Virtual functions must be implemented otherwise the linking will not work. So there will always be some kind of an implementation for virtual functions that the end user doesn't see. However, the interface is like a contractual obligation. Although there could be different ways of meeting the obligation, the obligation must be met somehow.
// ...snip...
struct Base
{
virtualvoid f() const { cout << "Base" << endl; }
virtual ~Base() {}
};
struct Derived : public Base
{
virtualvoid f() const { cout << "Derived" << endl; }
};
int main() {
srand( time( 0 ) );
int n = rand() % 100;
Base * p;
if( n % 2 == 0 ) {
p = new Base();
} else {
p = new Derived();
}
p->f(); // ?
delete p;
return 0;
}
Similarly, the type could be swapped during runtime or upon a particular event, including user input. Each time the program is run may have a different behavior.
(Note that runtime polymorphism uses objects on the free store and not just on the stack.)
Static polymorphism binds the symbol (p) at compilation time and it cannot vary without recompilation.
By the way, the idea behind polymorphism is to be able to perform operations on groups of similar objects uniformly. That is, they share a common interface (such as the function f above) that can be called independent of the actual type.