Virtual Functions and Runtime Polymorphism in C ++

Tram Ho

Virtual Functions and Runtime Polymorphism in C ++

1. Virtual Functions and Runtime Polymorphism

Consider the following simple program as an example of runtime polymorphism. The main thing to note in the program is that the class derived function is called using a base class pointer. Here the virtual functions are called according to the type of object pointed or referenced, not by the type of pointer or reference, meaning that the function call will be processed during the run not in the compiler.

Advantages of a virtual function:

Virtual functions allow you to create a list of base class pointers and methods called from a derived class without knowing exactly the object of the derived class.

Ex:

Consider a simple base class Employees, classes that contain virtual functions like growSalary (), transfer (), Promotion (), etc. Different types of employees like Manager, Engineering, etc. may have separate implementations for Virtual functions are present in the base employee class.

In our complete software, we simply pass a list of employees everywhere and call the appropriate functions without knowing the type of employee. For example, we can easily raise salaries for all employees by iterating through the employee list. Each type of employee may have their own logic in class, but we don’t need to worry about them because if Salary () is present for a specific type of employee, only that function will be called.

Virtual functions are so useful that later languages ​​like Java keep all methods virtual by default.

2. Virtual table mechanism and vptr pointer

  • Virtual table is a mechanism for making virtual function calls.
  • vtable: is an array of function pointers declared for each class.
  • vptr: is a pointer to vtable, declared for each object.

The compiler adds additional code in two places to maintain and use vptr.

  1. This code sets the vptr of the object to be created. This code sets vptr to point to the vtable of the class.
  1. With a polymorphic function call (e.g., e-> Promote () in the code above) Wherever function calls are made, the compiler inserts the code to find the previous vptr by using a pointer or base class reference (In the above example, because the object is called a derivative type, vptr). of the derived class accessed). When vptr is fetched, the vtable of the derived class can be accessed. Using vtable, the address of the derived class function is accessed and called.

This issue will be discussed in more detail in the following article.

Chia sẻ bài viết ngay

Nguồn bài viết : Viblo