当前位置:网站首页>Ask and answer: dispel your doubts about the virtual function mechanism
Ask and answer: dispel your doubts about the virtual function mechanism
2022-07-03 20:51:00 【Your dream is like smoke, Brian】
List of articles
- Q1: Virtual functions (virtual function) How is it realized ?
- Q2: What is a pure virtual function (pure virtual function)?
- Q3: Does pure virtual function occupy virtual function table ?
- Q4: Can a constructor be a virtual function or a pure virtual function ?
- Q5: Can virtual functions be called in constructors ?
- Q6: Why does the destructor of the base class need to be declared as a virtual function ?
- Q7: Virtual functions can be declared inline (inline) Function? ?
- Q8: Multiple inheritance (virtual inheritance) What is the change of the virtual function table under ?
- Q9: Virtual functions can be overloaded (overload) Do you ?
- Q10: What is the extra cost of using virtual function mechanism ?
Q1: Virtual functions (virtual function) How is it realized ?
Virtual function mechanism , Through the virtual function table (vtable) Realization . Only when a virtual function is declared in a class , The compiler will add a virtual function table for this class . The virtual function table holds the addresses of all virtual functions of the class . The object of the class that declares the virtual function will hold a pointer to the base address of the virtual function table .
How to maintain virtual function table ? There are mainly three situations :
- Derived class override (override) Virtual function of base class
The corresponding virtual function pointer in the base class is changed to the pointer of the virtual function of the derived class . - The derived class inherits the virtual function of the base class
The pointer of the virtual function corresponding to the derived class is set to the pointer of the virtual function corresponding to the base class - Derived classes implement new virtual functions ( That is, it has a different function signature from all virtual functions in the base class ( Pay attention to distinguish overloads
overload
And rewriteoverride
The concept of ).
Add , The pointer of the virtual function it implements .
Reference resources :
How are C++ objects laid out in memory? —— Bjarne Stroustrup’s C++ Style and Technique FAQ
Q2: What is a pure virtual function (pure virtual function)?
Concept :
- The declaration of a class function is followed by ”=0“, It is a pure virtual function .
- Pure virtual functions implicitly declare classes as abstract classes (abstract class)
- A class with at least one pure virtual function is called a pure virtual class . A class with only pure virtual functions is called C++ The interface (interface)
characteristic :
- Pure virtual classes cannot be instantiated .
- You must implement pure virtual functions in inherited pure virtual classes , Otherwise, the derived class is still a pure virtual class .
purpose :
- Occupy the pit : Make an appointment for “ Interface ” Delay the binding of the actual implementation to the run stage instead of the compilation stage .
See :
What is a pure virtual function? —— Bjarne Stroustrup’s C++ Style and Technique FAQ
Q3: Does pure virtual function occupy virtual function table ?
Pure virtual functions do occupy slots in their virtual function tables (slot) , But what is in the slot depends on the implementation of the compiler . generally speaking , The pointer in the slot is either assigned NULL
, Or take the address of the specific function generated by the compiler . Performing behavior similar to assertions in these functions causes the compiler to issue an error prompt .
reflection : Pure virtual functions have virtual function tables . Here is an interesting discussion . A pure virtual function even if it declares a virtual function , But pure virtual functions cannot be instantiated , So what's the significance of pure virtual classes having their own virtual function table ? Perhaps the virtual function table also includes support RTTI Required information .
See in detail :How are virtual functions and vtable implemented?
Q4: Can a constructor be a virtual function or a pure virtual function ?
no way .
Virtual invocation is a mechanism that allows you to complete the work while providing some information . Special , fictitious (virtual) It allows us to call functions when we only know the interface and do not know the exact type of object .
Creating an object requires complete information . Special , To create objects , We must know the exact type of the object .
Combine the characteristics of the two mechanisms , We know that the constructor cannot be a virtual function or a pure virtual function .
See : Why don’t we have virtual constructors?
Q5: Can virtual functions be called in constructors ?
Although you can call , But this is undefined behavior . You should not expect the program to run in the state you expect .
When calling a virtual function in a constructor , The object is in a state that is not fully constructed . Therefore, calling virtual functions in constructors does not perform runtime binding as expected , Instead, the corresponding virtual function of the class to which the constructor belongs will be called .
See : Can I call a virtual function from a constructor?
Q6: Why does the destructor of the base class need to be declared as a virtual function ?
Only when the base class has at least one virtual function , We should declare the destructor of the base class as a virtual function .
When the base class has virtual functions , It means that the behavior of the base class is designed as the interface of the derived class . under these circumstances , We usually assign the base class pointer to the object address of the derived class , Use delete
keyword . If the destructor of the base class is not declared as virtual
, Will cause the destructor of the derived class not to be called , This leads to memory leaks .
See : Why are destructors not virtual by default?
Q7: Virtual functions can be declared inline (inline) Function? ?
Can be declared as an inline function . generally speaking , Even ordinary functions are declared inline , The compiler may still ignore inline
identification .
There are additional requirements for inlining virtual functions . Only when virtual function calls do not produce dynamic parsing behavior , Will be expanded inline by the compiler . therefore , Only the compiler knows the exact object type of the virtual function being called , Virtual functions will be expanded inline .
This will only happen in
- Use the scope to avoid virtual function mechanism back and forth .
- Call virtual functions with actual objects instead of pointers and references to objects .
Reference resources :Are “inline virtual” member functions ever actually “inlined”?
Q8: Multiple inheritance (virtual inheritance) What is the change of the virtual function table under ?
Multiple inheritance Under the vtable Memory layout . The most common implementation is through multiple vtable Realization
verification :
The following derived classes D The instance size of is 64 Bit system 16 Bytes . So guess D Examples and DD Instances of both hold two vptr.
class B1{
virtual void funcB1(){
}
};
class B2{
virtual void funcB2(){
}
};
class D: public B1, B2{
};
class DD : public D{
};
D objD;
DD objDD;
sizeof(D) // 16 Bytes
sizeof(DD) // 16 Bytes
Add a test , Add one more B3 class , By D Inherit . Things have changed , Prove that our guess is correct . Test link
sizeof(D) // 24 Bytes
sizeof(DD) // 24 Bytes
all the minor details :
reflection : What about the layout under virtual inheritance ? How does virtual inheritance ensure that there is only one instance ?( Virtual inheritance (Virtual inheritance), Generally used to solve diamond inheritance The problem of .)
Q9: Virtual functions can be overloaded (overload) Do you ?
Sure .
for example :
class Base
{
public:
virtual void fun ( int x = 0)
{
cout << "Base::fun(), x = " << x << endl;
}
};
class Derived : public Base
{
public:
// error: 'virtual void Derived::fun(float)' marked 'override', but does not override
virtual void fun ( float x = 10.0 ) override
{
cout << "Derived::fun(), x = " << x << endl;
}
};
Getting rid of override
After the logo , Compilation can pass . Derived classes here Derived Of fun Functions are considered overloaded .
quote : Overloading of virtual functions
Q10: What is the extra cost of using virtual function mechanism ?
Time cost : The call cost is not different from that of ordinary functions , Compared with ordinary functions, it costs more to find functions in the virtual function table , But this kind of expense has little effect , The real extra cost is that the virtual function table may affect the compiler optimization .
Space overhead : Each class that declares virtual functions holds its own virtual function table . therefore , When the level of inheritance is deeper , The more memory overhead .
In addition : Use RTTI It is more expensive than the virtual function mechanism :
dynamic_cast In some cases, you need to recursively traverse the entire class inheritance hierarchy .
all the minor details :
reflection : C++ in RTTI How the mechanism works
Reference resources :
边栏推荐
- Set, weakset, map, weakmap in ES6
- Measurement fitting based on Halcon learning -- Practice [1]
- The 12th Blue Bridge Cup
- Wargames study notes -- Leviathan
- [postgresql]postgresql custom function returns an instance of table type
- jvm jni 及 pvm pybind11 大批量数据传输及优化
- Get log4net log file in C - get log4net log file in C
- How to handle wechat circle of friends marketing activities and share production and release skills
- Brief analysis of ref nerf
- Test access criteria
猜你喜欢
2.5 conversion of different data types (2)
Hcie security Day12: supplement the concept of packet filtering and security policy
Design e-commerce seckill system
Viewing Chinese science and technology from the Winter Olympics (II): when snowmaking breakthrough is in progress
APEC industry +: father of the king of the ox mill, industrial Internet "king of the ox mill anti-wear faction" Valentine's Day greetings | Asia Pacific Economic media | ChinaBrand
Go learning notes (4) basic types and statements (3)
In 2021, the global revenue of syphilis rapid detection kits was about US $608.1 million, and it is expected to reach US $712.9 million in 2028
@Transactional注解失效的场景
It is discussed that the success of Vit lies not in attention. Shiftvit uses the precision of swing transformer to outperform the speed of RESNET
Discussion Net legacy application transformation
随机推荐
@Scenario of transactional annotation invalidation
Rhcsa third day notes
LabVIEW training
Last week's content review
Use nodejs+express+mongodb to complete the data persistence project (with modified source code)
电子科技大学|强化学习中有效利用的聚类经验回放
淺析 Ref-NeRF
2022 melting welding and thermal cutting examination materials and free melting welding and thermal cutting examination questions
上周内容回顾
The global industrial design revenue in 2021 was about $44360 million, and it is expected to reach $62720 million in 2028. From 2022 to 2028, the CAGR was 5.5%
强化學習-學習筆記1 | 基礎概念
Fingerprint password lock based on Hal Library
XAI+网络安全?布兰登大学等最新《可解释人工智能在网络安全应用》综述,33页pdf阐述其现状、挑战、开放问题和未来方向
Do you really know how old you are?
【leetcode】1027. Longest arithmetic sequence (dynamic programming)
In 2021, the global revenue of thick film resistors was about $1537.3 million, and it is expected to reach $2118.7 million in 2028
Wireless network (preprocessing + concurrent search)
Design e-commerce seckill system
Link aggregation based on team mechanism
Research Report on the overall scale, major manufacturers, major regions, products and application segmentation of rotary tablet presses in the global market in 2022