What are virtual functions in c?

Answer:

Answer

A virtual method is a method that you should override when inheriting that class

It uses virtual as a keyword.

Answer

Virtual functions allow polymorphism. If a function is not declared virtual it will be impossible to override it in a child class. Example:

class Foobar
{

public:

int i;
Foobar() {i = -1;}
virtual void FuncA() {i = 0;}
void FuncB() {i = 10;}

};

class Foo: public Foobar
{

public:

virtual void FuncA() {i = 1;}
void FuncB() {i = 11;}

};

class Bar: public Foobar
{

public:

virtual void FuncA() {i = 2;}
void FuncB() {i = 12;}

};

void FoobarFunc(Foobar* fb)
{

cout << fb->i << endl;
fb->FuncA();
cout << fb->i << endl;
fb->FuncB();
cout << fb->i << endl << endl;

}

void FooFunc(Foo* f)
{

cout << f->i << endl;
f->FuncA();
cout << f->i << endl;
f->FuncB();
cout << f->i << endl << endl;

}

When FoobarFunc is called with Foo, Bar, or Foobar, the line fb->FuncA() will call the the correct FuncA from each class according to polymorphism. However, in FoobarFunc, the line fb->FuncB() will ALWAYS call Foobar's FuncB no matter what type is actually passed in. To further illustrate this, in FooFunc, the line f->FuncB() will ALWAYS call Foo's FuncB.

First answer by ComputerJy. Last edit by Sudennis315. Contributor trust: 30 [recommend contributor recommended]. Question popularity: 20 [recommend question].