Can we achieve runtime polymorphism(method overriding) without virtual function in C++
I think that since it is runtime it should only be possible through pointers using virtual functions but we can override a function without virtual function and pointers also. Here is the following code.. But will it still be runtime ?
#include <iostream>
using namespace std;
class animal{
public:
void print(){
cout<<"I am animal"<<endl;
}
};
class dog: public animal{
public:
void print(){
cout<<"I am dog"<<endl;
}
};
class cat:public animal{
public:
void speak(){
cout<<"meow"<<endl;
}
};
int main()
{
dog obj1;
obj1.print(); // I am a dog
cat obj2;
obj2.print(); // I am animal
return 0;
}
It's certainly true that you can't override a method without virtual functions, as one of the comments mentioned. To achieve any kind of runtime polymorphism, you will need some kind of lookup table either implemented yourself or by the compiler. A relatively recent alternative to virtual functions is to use variants instead. Another great blog post compares virtual functions to std::variant. To quote:
Example code
Also illustrates another quote from the blog post