You are here:

C++/Virtual functions

Advertisement


Question
What are virtual functions and how to implement them in C?


Answer
Hello Meghaldevi, thank you for the question.

A virtual function is a C++ function that is bound to an invoking object at run time and implicitly called correctly. Here is an example:

class A
{
public:
A();
~A();

virtual void print() {std::cout << 'A';}
}

class B : public A
{
public:
B();
~B();
virtual void print() {std::cout << 'B';}
}

class C : public A
{
public:
C();
~C();
virtual void print() {std::cout << 'C';}
}

int main()
{
A *a = new B;
a->print();
}

The call to print will correctly call the B classes print function, due to the virtual binding.

virtual is a strictly C++ feature. The way to do it in C would be to construct a huge table of function pointers that would call correct functions, but that is by no means an easy task.

I hope this information was helpful.

- Eddie

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Eddie

Expertise

I can answer questions about the C++ language, object oriented design and architecture. I am knowledgable in a lot of the math that goes into programming, and am certified by ExpertRating.com. I also know a good deal about graphics via OpenGL, and GUIs.

Experience

I have completed numerous games and demos created with the C++ programming language. Currently employed as a software engineer in the modeling and simulation field. I have about 7 years experience.

©2016 About.com. All rights reserved.