I was reading about function overriding and run-time polymorphism online.
While reading I found an example of function overriding on programiz where following example was given :
// C++ program to demonstrate function overriding
#include <iostream>
using namespace std;
class Base {
public:
void print() {
cout << "Base Function" << endl;
}
};
class Derived : public Base {
public:
void print() {
cout << "Derived Function" << endl;
}
};
int main() {
Derived derived1;
derived1.print();
return 0;
}
Output
Derived Function
Here in Derived class we have modified print() function of Base class and is accessed by an object derived1 of the derived class.
A question stuck in my mind - is this an example of runtime polymorphism also? or operator overriding not always comes under runtime polymorphism as I have read this somewhere
The main use of virtual function is to achieve Runtime Polymorphism.Runtime polymorphism can be achieved only through a pointer (or reference) of base class type.
Hence my question is - "Is this an example of run-time polymorphism as does not use the virtual keyword and involves a pointer to base class and even an example of function overriding?
Correct me if I have mentioned anything wrong.
Base::print()function to bevirtual.Base::printis not virtual. There are two independent, unrelated functionsBase::printandDerived::print. In particular,Derived derived1; Base* p = &derived1; p->print();would callBase::print; whereas ifprintwere virtual, this would have calledDervied::print(that's the whole point of polymorphism). Neither class in your example is a polymorphic class; there is no polymorphism at all.Base *base = new Derived;and then declareprintasvirtual.