Virtual function tables

Virtual function tables

Question:
I would like to know what virtual function tables are. When one refers to vtables, is it a virtual function table that is implied?

Answer:
In short, vtables are how most C++ compilers implement polymorphism, which means to take on many forms. In the context of C++, it is when you do not have full knowledge of the type (class) at compile time.

In essence, you have a pointer to a base class at compile time that will point to a derived class instance at runtime. Next, the function your base class pointer is calling is dynamically binded at runtime to the derived class instance that your base class pointer is referencing.

For this to be possible, you must define such functions as virtual in the base class. As a result, all derived classes will also treat such member functions as virtual (see code extract below).

In your code somewhere, the following classes are defined:

Canine is the base class, and Dog and Wolf derive from Canine. Notice the Bark member function is declared as virtual. You could include the virtual keyword in Dog and Wolf for clarity, but it isn’t necessary. Once a function is defined as virtual in a base class, it will be virtual in all base class descendants, as is the case in Dog and Wolf.

class Canine{public:	virtual void Bark( ) { cout << "do nothing" << endl; }	...};class Dog : public Canine{	void Bark( ) { cout << "dog bark." << endl; }};class Wolf: public Canine {	void Bark( ) { cout << "wolf bark" << endl; }
Next, you may contain consumer code similar to the following:
//somewhere in my code.cpp file…void StartBarking(Canine* pCanine){	pCanine->Bark( );}void main ( ){// Imagine the canine types coming from a collection or database at runtimeDog* pDog =3D new Dog;Wolf* pWolf =3D new Wolf;// Next, your code simply reads those values in and calls the StartBarking function, which you have defined.StartBarking( pDog );StartBarking( pWolf );…}
Based on the code extract above, the StartBarking function takes a pointer to the Canine object. Canine is the base. The compile time code looks like this:
pCanine->Bark( );
At runtime, however, pCanine could be pointing to any descendent of the Canine class; hence, without you having to explicitly identify which Canine it is, the compiler will dynamically bind the appropriate Bark function to the Canine descendent class instance that pCanine is referencing. Remember, this is possible because the Bark function is defined as virtual in the Canine base class. If Bark was not defined as virtual, polymorphism would not exist because although the base class pointer is pointing to an instance of a descendent class, it would be unaware of the Bark function in the descendent, and would call the base class version instead, producing an undesirable result.

The virtual keyword indicates to the C++ compiler that it must create a vtable for the base class and all other classes that derive from it. A vtable is table in memory of pointers to functions defined as virtual in a given class, thus the name vtable (virtual function table).

There will always be one vtable per class (type) in memory. Each instance of the same class contains a pointer to the same vtable. Said another way, multiple objects of the same type share the same vtable. At runtime, pCanine will determine if the function being invoked is virtual. If so, it looks in the vtable of the object instance it is referencing, which will contain a pointer to the function that must be invoked.

When you re-implement a virtual function in a derived class, you are doing what is referred to as overriding the behavior of the base class function, which is what has been illustrated in code example above (both Dog and Wolf override the Bark virtual function). However, you may find in some cases that there is no need to override a virtual function if the descendent simply performs the same behavior as its ancestor (base) class.

Whether you override a virtual function in a derived class or not, it will have its own vtable with the same amount of entries as its base class. The difference is, virtual functions that are overridden will have pointers to functions in the vtable that refer to unique addresses, but virtual functions that are not overridden with have pointers to functions with the same address of the virtual functions originally defined in the base class. Therefore, keep in mind that utilizing polymorphism in C++ has the overhead of a vtable in memory for each class that contains virtual functions, and classes that derive from classes that contain virtual functions,whether or not you override those functions. However, this is a small price to pay to have a true object-oriented application, which essentially does not exist without polymorphism.

devx-admin

devx-admin

Share the Post:
Apple Tech

Apple’s Search Engine Disruptor Brewing?

As the fourth quarter of 2023 kicks off, the technology sphere is abuzz with assorted news and advancements. Global stocks exhibit mixed results, whereas cryptocurrency

Revolutionary Job Market

AI is Reshaping the Tech Job Market

The tech industry is facing significant layoffs in 2023, with over 224,503 workers in the U.S losing their jobs. However, experts maintain that job security

Foreign Relations

US-China Trade War: Who’s Winning?

The August 2023 visit of Gina Raimondo, the U.S. Secretary of Commerce, to China demonstrated the progress being made in dialogue between the two nations.

Pandemic Recovery

Conquering Pandemic Supply Chain Struggles

The worldwide coronavirus pandemic has underscored supply chain challenges that resulted in billions of dollars in losses for automakers in 2021. Consequently, several firms are

Game Changer

How ChatGPT is Changing the Game

The AI-powered tool ChatGPT has taken the computing world by storm, receiving high praise from experts like Brex design lead, Pietro Schirano. Developed by OpenAI,

Apple Tech

Apple’s Search Engine Disruptor Brewing?

As the fourth quarter of 2023 kicks off, the technology sphere is abuzz with assorted news and advancements. Global stocks exhibit mixed results, whereas cryptocurrency tokens have seen a substantial

GlobalFoundries Titan

GlobalFoundries: Semiconductor Industry Titan

GlobalFoundries, a company that might not be a household name but has managed to make enormous strides in its relatively short 14-year history. As the third-largest semiconductor foundry in the

Revolutionary Job Market

AI is Reshaping the Tech Job Market

The tech industry is facing significant layoffs in 2023, with over 224,503 workers in the U.S losing their jobs. However, experts maintain that job security in the sector remains strong.

Foreign Relations

US-China Trade War: Who’s Winning?

The August 2023 visit of Gina Raimondo, the U.S. Secretary of Commerce, to China demonstrated the progress being made in dialogue between the two nations. However, the United States’ stance

Pandemic Recovery

Conquering Pandemic Supply Chain Struggles

The worldwide coronavirus pandemic has underscored supply chain challenges that resulted in billions of dollars in losses for automakers in 2021. Consequently, several firms are now contemplating constructing domestic manufacturing

Game Changer

How ChatGPT is Changing the Game

The AI-powered tool ChatGPT has taken the computing world by storm, receiving high praise from experts like Brex design lead, Pietro Schirano. Developed by OpenAI, ChatGPT is known for its

Future of Cybersecurity

Cybersecurity Battles: Lapsus$ Era Unfolds

In 2023, the cybersecurity field faces significant challenges due to the continuous transformation of threats and the increasing abilities of hackers. A prime example of this is the group of

Apple's AI Future

Inside Apple’s AI Expansion Plans

Rather than following the widespread pattern of job cuts in the tech sector, Apple’s CEO Tim Cook disclosed plans to increase the company’s UK workforce. The main area of focus

AI Finance

AI Stocks to Watch

As investor interest in artificial intelligence (AI) grows, many companies are highlighting their AI product plans. However, discovering AI stocks that already generate revenue from generative AI, such as OpenAI,

Web App Security

Web Application Supply Chain Security

Today’s web applications depend on a wide array of third-party components and open-source tools to function effectively. This reliance on external resources poses significant security risks, as malicious actors can

Thrilling Battle

Thrilling Battle: Germany Versus Huawei

The German interior ministry has put forward suggestions that would oblige telecommunications operators to decrease their reliance on equipment manufactured by Chinese firms Huawei and ZTE. This development comes after

iPhone 15 Unveiling

The iPhone 15’s Secrets and Surprises

As we dive into the most frequently asked questions and intriguing features, let us reiterate that the iPhone 15 brings substantial advancements in technology and design compared to its predecessors.

Chip Overcoming

iPhone 15 Pro Max: Overcoming Chip Setbacks

Apple recently faced a significant challenge in the development of a key component for its latest iPhone series, the iPhone 15 Pro Max, which was unveiled just a week ago.

Performance Camera

iPhone 15: Performance, Camera, Battery

Apple’s highly anticipated iPhone 15 has finally hit the market, sending ripples of excitement across the tech industry. For those considering upgrading to this new model, three essential features come

Battery Breakthrough

Electric Vehicle Battery Breakthrough

The prices of lithium-ion batteries have seen a considerable reduction, with the cost per kilowatt-hour dipping under $100 for the first occasion in two years, as reported by energy analytics

Economy Act Soars

Virginia’s Clean Economy Act Soars Ahead

Virginia has made significant strides towards achieving its short-term carbon-free objectives as outlined in the Clean Economy Act of 2020. Currently, about 44,000 megawatts (MW) of wind, solar, and energy

Renewable Storage Innovation

Innovative Energy Storage Solutions

The Department of Energy recently revealed a significant investment of $325 million in advanced battery technologies to store excess renewable energy produced by solar and wind sources. This funding will

Renesas Tech Revolution

Revolutionizing India’s Tech Sector with Renesas

Tushar Sharma, a semiconductor engineer at Renesas Electronics, met with Indian Prime Minister Narendra Modi to discuss the company’s support for India’s “Make in India” initiative. This initiative focuses on

Development Project

Thrilling East Windsor Mixed-Use Development

Real estate developer James Cormier, in collaboration with a partnership, has purchased 137 acres of land in Connecticut for $1.15 million with the intention of constructing residential and commercial buildings.

USA Companies

Top Software Development Companies in USA

Navigating the tech landscape to find the right partner is crucial yet challenging. This article offers a comparative glimpse into the top software development companies in the USA. Through a

Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in and explore the leaders in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India, and kickstart your journey to

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner for your online project. Your

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the state. A Senate committee meeting

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor supply chain and enhance its