From what I learned so far, there are two kinds of polymorphism, compile-time, and runtime. In compile-time, the polymorphed function or operator is resolved by compiler, while in runtime, its resolved at runtime. Examples of compiile time polymorphism include function and operator overloading, and runtime polymorphism includes function overriding and virtual functions. Additonally there are cases like Early binding and Late binding which I'm coming to later. Consider the following code:
class base {
public:
void Print() {
std::cout << "This is parent class\n";
}
};
class derived : public base {
public:
void Print() {
std::cout << "This is derived class\n";
}
};
If I do this:
base b1;
b1.Print();
derived d1;
d1.Print();
the result is pretty obvious:
This is parent class
This is derived class
The real problem begins when I use a pointer to base class to operate on these functions.
base b1;
derived d1;
base* pb = &b1;
base* pb2 = &d1;
pb->Print();
pb2->Print();
The output would be:
This is parent class
This is parent class
This is due to Early binding, the compiler checks the type of object that is calling the function, not the type of object its processing. And pretty much obviously it is done in compile time. Now if I use the virtual
keyword in the base class function definition, then I can do the above easily without any hassle, which is due to Late binding, which saves the function definition for runtime based on the type of object its processing. This is an example of runtime polymorphism.
Sorry for taking too long, my question is, is this the only way we can achieve runtime polymorphism? Also, if function overriding is runtime polymorphism, then the previous example (i.e, the one with Early binding) should also be runtime polymorphism since it is also doing function overriding.