当前位置:网站首页>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
overloadAnd rewriteoverrideThe 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 :
边栏推荐
- Basic number theory -- Chinese remainder theorem
- 一台服务器最大并发 tcp 连接数多少?65535?
- 2.7 format output of values
- @Scenario of transactional annotation invalidation
- Assign the CMD command execution result to a variable
- 全网都在疯传的《老板管理手册》(转)
- @Transactional注解失效的场景
- Battle drag method 1: moderately optimistic, build self-confidence (1)
- 11-grom-v2-05-initialization
- [Yugong series] February 2022 Net architecture class 004 ABP vNext used in WPF project
猜你喜欢

Discussion Net legacy application transformation

2.2 integer

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%
![Measurement fitting based on Halcon learning -- Practice [1]](/img/71/9f6c27aa89035b2550bdb0ac902045.jpg)
Measurement fitting based on Halcon learning -- Practice [1]
![C 10 new feature [caller parameter expression] solves my confusion seven years ago](/img/32/2d81237d4f1165f710a27a7c4eb1e1.jpg)
C 10 new feature [caller parameter expression] solves my confusion seven years ago

你真的知道自己多大了吗?

XAI+网络安全?布兰登大学等最新《可解释人工智能在网络安全应用》综述,33页pdf阐述其现状、挑战、开放问题和未来方向

Apprentissage intensif - notes d'apprentissage 1 | concepts de base

Battle drag method 1: moderately optimistic, build self-confidence (1)

18、 MySQL -- index
随机推荐
The 12th Blue Bridge Cup
Example of peanut shell inner net penetration
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
Recommendation of books related to strong foundation program mathematics
Plan for the first half of 2022 -- pass the PMP Exam
LabVIEW training
Camera calibration (I): robot hand eye calibration
How to modify the network IP addresses of mobile phones and computers?
运维各常用命令总结
Do you really know how old you are?
浅析 Ref-NeRF
"Actbert" Baidu & Sydney University of technology proposed actbert to learn the global and local video text representation, which is effective in five video text tasks
Transformation between yaml, Jason and Dict
Test changes in Devops mode -- learning and thinking
你真的知道自己多大了吗?
Hcie security Day10: six experiments to understand VRRP and reliability
Wireless network (preprocessing + concurrent search)
Phpexcel import export
Fingerprint password lock based on Hal Library
Strange way of expressing integers (expanding Chinese remainder theorem)