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

How C++ accesses polymorphic objects through pointers or references

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article mainly explains how C++ accesses polymorphic objects through pointers or references, which interested friends may wish to have a look at. The method introduced in this paper is simple, fast and practical. Let the editor take you to learn how C++ accesses polymorphic objects through pointers or references.

Access polymorphic objects through pointers or references

Reason (reason)

If you have a class with a virtual function, you don't (in general) know which class provided the function to be used.

If a class has a virtual function, you usually don't know which (derived) class provides the function you are using.

Example (example) struct B {int a; virtual int f (); virtual ~ B () = default}

Struct D: B {int b; int f () override;}

Void use (BB)

{

D d

Bb2 = d; / / slice

Bb3 = b

}

Void use2 ()

{

D d

Use (d); / / slice

}

Both ds are sliced.

Both d (in the function) are cut off (because the derived class object assigns values to the base class object)

Exception (exception)

You can safely access a named polymorphic object in the scope of its definition, just don't slice it.

You can safely use the variable name in the scope where the polymorphic object is defined, as long as you are careful not to be cut off.

Void use3 ()

{

D d

D.F (); / / OK

}

See also (see)

A polymorphic class should suppress copying (polymorphic classes should suppress replication)

Enforcement

Flag all slicing. (Mark the operation of data cutoff)

At this point, I believe you have a better understanding of "how C++ accesses polymorphic objects through pointers or references". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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

Internet Technology

Wechat

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

12
Report