A simple Example of C++ Virtual Keyword
Virtual keyword determines if a member function of a class can be over-ridden in its derived classes. Here is a simple example to show this.
#include <iostream> using namespace std; class Car // Base class for C++ virtual function example { public: virtual void Create() // virtual function for C++ virtual function example { cout << "Parent class: Car\n"; } }; class Sedan: public Car { public: void Create() { cout << "Derived class: Sedan - Overridden C++ virtual function"; } }; int main() { Car *x, *y; x = new Car(); x->Create(); y = new Sedan(); y->Create(); } |
This is produce the result of:
Parent class: Car
Derived class: Sedan - Overridden C++ virtual function
By simply remove the keyword "virtual", the result would be:
Parent class: Car
Parent class: Car
The non-virtual member functions are resolved at compiling time and it's called static binding. However, the c++ virtual member functions are resolved during runtime and it's called as dynamic binding.
This is different with Java. Here is a post about comparison of Java and C++.
<pre><code> String foo = "bar"; </code></pre>
-
ajaychowdary
-
Pixel
-
anand
-
Ankit
-
Ankit