Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Summary of the implementation principle of Polymorphism in C++ Compiler

2025-02-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >

Share

Shulou(Shulou.com)06/01 Report--

Question: define an empty type without any member variables or member functions, and sizeof this type, what is the result?

The result is 1, because instances of empty types do not contain any information, so the result is 0 after sizeof calculation, but when declaring instances of any type, you must have a certain amount of space in memory, otherwise these instances cannot be used, and it is up to the compiler to decide how much memory to occupy.

Continue to ask: if you add a constructor and destructor to this type, what is the result?

Or 1, because we only need to know the address of the function when we call the constructor and destructor, and the address of these functions is only related to the type and has nothing to do with the instance of the type. The compiler will not add any additional information to the instance for these two functions.

Continue to ask: what if you turn a destructor into a virtual function? What's the result?

When the C++ compiler finds a virtual function in the type, it generates a virtual function table for the type and adds a pointer to the virtual function table in each instance of the type. on a 32-bit machine, the pointer type size is 4 bytes. The result is that on a 4Jing 64-bit machine, the pointer size is 8 bytes, and the result is 8.

The implementation effect of object-oriented Polymorphism

Polymorphism: the same call statement has many different forms of expression.

Take a look at the following code example:

Class animal {public: void sleep () {cout

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Network Security

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report