I\'m learning C++ and I\'m just getting into virtual functions.
From what I\'ve read (in the book and online), virtual functions are functions in the base class that
Need for Virtual Function explained [Easy to understand]
#include
using namespace std;
class A{
public:
void show(){
cout << " Hello from Class A";
}
};
class B :public A{
public:
void show(){
cout << " Hello from Class B";
}
};
int main(){
A *a1 = new B; // Create a base class pointer and assign address of derived object.
a1->show();
}
Output will be:
Hello from Class A.
But with virtual function:
#include
using namespace std;
class A{
public:
virtual void show(){
cout << " Hello from Class A";
}
};
class B :public A{
public:
virtual void show(){
cout << " Hello from Class B";
}
};
int main(){
A *a1 = new B;
a1->show();
}
Output will be:
Hello from Class B.
Hence with virtual function you can achieve runtime polymorphism.