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

5 thoughts on “A simple Example of C++ Virtual Keyword”

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

  2. 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();

Leave a Comment