Click here to Skip to main content
16,004,653 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi can any one simplify the idea of virtual or have any example-code for it's way of usage
Posted

The virtual keyword tells the compiler to generate a virtual table for the class and to put the function address into that table.

All derived classes will also have virtual tables with the address of the function that is in the base class or if overridden, the address of the function in the derived class.

A pure virtual functions tells the compiler not to instantiate the class.
That means fail all attempts to create an object of the class.

I have this article that might help you understand it better - Polymorphism in C[^]
 
Share this answer
 
Virtual functions make it possible to call a function on a base class and have that call be "forwarded" through to the derived class. Here is an example (it's written in C#, but the principles are the same as in C++):
C#
// Note the dog is stored as an animal.
Animal someAnimal = new Dog();
someAnimal.Move(); // "I am a moving dog."
someAnimal.Eat();  // "I am an eating animal."

// Base class.
public class Animal
{
	// Virtual function.
	public virtual void Move()
	{
		MessageBox.Show("I am a moving animal.");
	}
	// Non-virtual function.
	public void Eat()
	{
		MessageBox.Show("I am an eating animal.");
	}
}

// Derived class.
public class Dog : Animal
{
	public override void Move()
	{
		MessageBox.Show("I am a moving dog.");
	}
	public void Eat()
	{
		MessageBox.Show("I am an eating dog.");
	}
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900