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
	virtual void Create() // virtual function for C++ virtual function example
		cout << "Parent class: Car\n";
class Sedan: public Car {
	void Create() {
		cout << "Derived class: Sedan - Overridden C++ virtual function";
int main() {
	Car *x, *y;
	x = new Car();
	y = new Sedan();

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++.

Category >> C/C++  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";
  • ajaychowdary

    Awsome example

  • Pixel

    Nice, Sweet and simple explanation.

  • anand

    class A{
    void h(void){

    class B: public A{
    void h(int x){

    int _tmain(int argc, _TCHAR* argv[])
    B *b = new B();
    return 0;

    Compile time error:
    error C2660: ‘B::h’ : function does not take 0 arguments

    Why it so? Can some one help me

  • Ankit

    1 more thing..i am new to c++…what if i take this code without virtual keyword and uses this

    car *x;
    sedan *y;
    x=new car();
    y=new sedan();

  • Ankit

    very much helpful
    much simple and accurate example…