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

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

  1. Ankit on 2012-7-31

    very much helpful
    much simple and accurate example…

  2. Ankit on 2012-7-31

    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();
    x->create();
    y->create();

  3. anand on 2012-9-27

    class A{
    public:
    void h(void){
    printf(“hello”);
    }
    };

    class B: public A{
    public:
    void h(int x){
    printf(“%d”,x);
    }
    };

    int _tmain(int argc, _TCHAR* argv[])
    {
    B *b = new B();
    b->h();
    return 0;
    }

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

    Why it so? Can some one help me

  4. Pixel on 2013-9-9

    Nice, Sweet and simple explanation.

  5. ajaychowdary on 2013-10-8

    Awsome example

Leave a comment

*