"How is Runtime Polymorphism achieved in C++?" one of my friends inquired.
"By Inheritance," I replied.
"No, it can only be done with virtual functions," he said.
As a result, I gave him the following code as an example:-
#include<iostream>
using namespace std;
class A
{
public:
int i;
A(){i=100;}
};
class B : public A
{
public:
int j;
B(){i = -1; j = 99;}
};
void func(A& myA)
{
cout<<myA.i << endl;
}
int main()
{
B b;
A* a = new B();
func(*a);
func(b);
delete a;
return 0;
}
We can print the value of public member I using the function func(), which takes a reference to A but accepts an object from B.
Compile time polymorphism, he explained.
My inquiries are as follows:
1) Is virtual function polymorphism the only way to achieve runtime polymorphism?
2) Is the above example polymorphic at runtime or at compile time?
3) In the event that I have the following code:
void func2(A& myA)
{
cout << myA.i << endl;
// dynamic/static cast myA to myB
cout<<myB.j << endl;
}
Is it a polymorphism of some sort?
Is it polymorphism, or something else?