Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the virtual keyword needed?

Tags:

c++

virtual

In other words, why doesn't the compiler just "know" that if the definition of a function is changed in a derived class, and a pointer to dynamically allocated memory of that derived class calls the changed function, then that function in particular should be called and not the base class's?

In what instances would not having the virtual keyword work to a programmer's benefit?

like image 432
Bob John Avatar asked Nov 28 '12 08:11

Bob John


People also ask

What is the use of virtual keyword in C++?

A virtual keyword in C++ is used to create a virtual function in C++. The virtual function is the parent class function which we want to redefine in the child class. The virtual function is declared by using the keyword virtual.

Is virtual keyword mandatory?

To override a method, the override keyword is mandatory not virtual . The difference is that you hide the method if you omit the virtual keyword, and not override it.

Is virtual keyword necessary in C#?

In Java, methods are virtual by default. In C#, they are not, and must be marked as virtual in order for polymorphism to work.

What is the meaning of virtual keyword?

The virtual keyword is used to modify a method, property, indexer, or event declaration and allow for it to be overridden in a derived class.


2 Answers

virtual keyword tells the compiler to implement dynamic dispatch.That is how the language was designed. Without such an keyword the compiler would not know whether or not to implement dynamic dispatch.

The downside of virtual or dynamic dispatch in general is that,

  • It has slight performance penalty. Most compilers would implement dynamic dispatch using vtable and vptr mechanism, where the appropriate function to call is decided through vtable and hence an additional indirection is needed in case of dynamic dispatch.
  • It makes your class Non-POD.
like image 50
Alok Save Avatar answered Nov 14 '22 23:11

Alok Save


One reason:

Consider base classes located in separate module, like library.

And derived classes in your application.

How would compiler knows during compiling the library that the given function is/must be virtual.

like image 21
PiotrNycz Avatar answered Nov 14 '22 23:11

PiotrNycz