The C + + object model----about objects

Source: Internet
Author: User
Tags compact

1.3 Objects of difference (an object distinction) C + + program design model directly supports three kinds of programming paradigms (Program design paradigm)
1. The program model (procedural models) is like C, C + + of course, it supports it, string processing is an example, you can use a character array and a set of str* functions:
Char boy[] = "Danny"; char *p_son;...p_son = new Char[strlen (boy) + 1];strcpy (P_son, Boy) ... if (!strcmp (P_son, boy))    t Ake_to_disneyland (boy);
2. Abstract data type model, ADT the model so-called "abstraction" is provided with a set of expressions (the public interface), and its operation definition is not explicit, such as the following String class:
String girl = "Anna"; String daughter;...//string::operator= ();d aughter = girl;...//string::operator== (); if (girl = = daughter)    take_to _disneyland (girl);
3. Object-oriented models (object-oriented model) There are some interrelated models in this model that are encapsulated by an abstract base class (to provide a common interface). Library_materials class is an example where real subtypes such as book, Video, and so on can be derived from:
void Check_in (Library_materials *pmat) {    if (pmat->late ())        pmat->fine ();    Pmat->check_in ();    if (Lender *plend = pmat->reserved ())        pmat->notify (plend);}
Writing a program purely in a paradigm helps to consolidate the overall behavior, but if mixed with different paradigms, it can have a frightening effect, especially if there is no care to handle it. The most common negligence occurs in a specific entity with a base class such as:
Library_materials thing1;
To complete a polymorphic (polymorphism) Situation:
Class Book:public Library_materials {...}; Book book;//thing1 is not a book,book to be cut (sliced), but Thing1 still maintains a library_materials.thing1 = book;//call Library_materials:: Check_in () thing1.check_in ();
Instead of using base class pointer or reference to accomplish polymorphic situations:
Library_materials &thing2 = book;thing2.check_in ();
Although a base class object in the inheritance system can be processed directly or indirectly,The polymorphic properties required for OO programming are supported only through indirect processing by pointer or reference.。 The definition and application of thing2 in the last example is a good example of OO paradigm. The definition and application of thing1 has escaped the habit of Oo, which reflects the good behavior of an ADT paradigm. Thing1 's behavior is good or bad, depending on the programmer's intentions.
AlthoughThe polymorphic operation of object requires that this object be accessible via a pointer or reference, whereas the processing of pointer or reference in C + + is not a necessary result of polymorphism。 As shown below:
There is no polymorphism because the operand is not a class Objectint *pi;//class X is treated as a base class (can have polymorphic effects) x *px;
In C + +, polymorphism exists only in the public class system, for example PX may point to an object of the self type, or to a type derived from public. NonPublic's derived behavior, and pointers of type void*, can be said to be polymorphic, but they are not explicitly supported by the language, meaning they must be managed by the programmer through explicit conversion operations.
The following methods of C + + support polymorphism: 1. Through a set of implicit conversion operations such as converting a derived class pointer to a pointer to its public base type:
    Shape *ps = new Circle ();
2. Via the virtual function mechanism
    Ps->rotate ();
3. Via the dynamic_cast and typied operators
    if (Circle *pc = Dynamic_cast<circle *> (PS))
The main use of polymorphism is to influence the encapsulation of types through a common interface, which is usually defined in an abstract base class。 For example, Library_materials class defines an interface for subtype such as book, Vedio, and so on. This oneThe shared interface is triggered by the virtual function mechanism, which resolves which function entity is called at execution time based on the true type of object., through this operation:
Library_material->check_out ();
The code avoids the "materials of a particular library" and causes the change to be unpaid, not only that "the program code does not need to change when the type has been added, modified, deleted," but also makes a new library_materials The subtype provider does not need to rewrite the behavior and operations that are common to all types in the inheritance system.
Consider the following code:
void rotate (x datum, const x *pointer, const x &reference) {    //before the execution period, it is not possible to decide which rotate () entity to invoke (    *pointer). Rotate ();    Reference.rotate ();        The following operation always calls X::rotate ()    datum.rotate ();} Main () {    Z Z;    Z is a subtype of x        rotate (z, &z, z);    return 0;}
The two "function call pointers" completed by pointer and reference are dynamically completed. In this case, they all call Z::rotate (), and the "function call operation" done via datum may (or may not) pass through the virtual mechanism. However, it always calls X::rotate (). (This is the so-called "compilation Literacy" issue: Regardless of the virtual function that is called by datum, the result is the same from the semantics)
How much memory is needed to represent a class object?Generally, there are:
The sum size of its nonstatic data members
Add any space (padding) that is filled (possibly between members or at the aggregate boundary) due to the need for alignment (to adjust the value to multiples of an integer)
Plus any additional burden generated by the interior in order to support virtual (overhead)

A pointer regardless of which data type it points to, the size of the memory required by the pointer itself is fixed, as follows:
Class Zooanimal {public:    zooanimal ();    Virtual ~zooanimal ();    // ...    virtual void rotate ();p rotected:    int loc;    string name;}; Zooanimal za ("Zoey"); Zooanimal *pza = &za;
The possible layout of the class object za and pointer pza is LOC (1000~1003), name (1004~1011), virtual (1012~1015).
The type of the pointer (the type of a Pointer) how does a pointer to zooanimal differ from a pointer to an integer or a pointer to a template array?
Zooaimal *px;int *pi; Array<string> *pta;
In terms of memory requirements, there is no difference. All three of them need to have enough memory to hold a machine address.The difference between "pointing to different types of pointers" is not that the pointer notation differs, nor that its contents (representing an address) are different, but rather that the type of object it addresses is different. that is,the pointer type instructs the compiler how to interpret the memory content and its size in a particular address.
1. An integer pointer to address 1000, on a 32-bit machine, will cover the address space 1000~1003
2. If the string is a traditional 8-bytes (including a 4-bytes character pointer and an integer used to represent the length of the string), then a zooanimal pointer spans the address space 1000~1015 (4+8+4)
So, what address space will be covered by a pointer to 1000 and the type void *?
I don't know. This is why a pointer of type void * can contain only one address, and cannot manipulate the cause of the object it refers to
So Transformation (CAST)is actually a compiler command, in most cases it does not change the actual address contained in a pointer, it only affects the "size of the indicated memory and its memory" interpretation method
After adding polymorphism (add polymorphism) now defines a bear, as a zooanimal, of course, through "public inheritance" can be done.
Class Bear:public Zooanimal {public: Bear    ();    ~bear ();    // ...    void rotate ();    virtual void dance ();    ... protected:    enum Dances {...}    Dances Dances_known;    int cell_block;}; Bear B ("Yogi"); Bear *PB = &b; Bear &rb = *PB;
What kind of memory requirements will B,PB,RB have? Either pointer or reference requires only one word space (4-bytes on 32-bit machines). Bear object requires a bytes, which is the bytes of zooanimal plus the 8 bytes brought by Bear.
Suppose the Bear object is at address 1000, what is the difference between a bear pointer and a zooanimal pointer?
Bear B; Zooanimal *pz = &b; Bear *PB = &b;
Each of them points to the first byte of the Bear object, in which the difference is that the address covered by PB contains the entire Bear object, and that the address contained in the PZ contains only the Zooanimal subobject in the.
In addition to the members appearing in Zooanimal Subobject, it is not possible to use PZ to directly process any members of the bear. The only exception is through the virtual mechanism:
Illegal: Cell_block is not a member of Zooanimal, although PZ currently points to a bear objectpz->cell_block;//OK: After a display of the downcast operation there is no problem (bear *) PZ)->cell_block;//under such a better, but it is a run-time operation (higher cost) if (bear *pb2 = Dynamic_cast<bear *> (PZ))    pb2- >cell_block;//OK: Because Cell_block is a memberpb->cell_block; of bear
If you write the following statement
Pz->rotate ();
, the type of PZ will determine the following two points at compile time:
Fixed available interface, PZ can only invoke the public interface of Zooanimal
Access level for this interface (for example, rotate () is a public member of Zooanimal)
At each execution point, the type of object that PZ refers to determines the entity that the rotate () invokes. the encapsulation of type information is not maintained in the PZ, but is maintained in link, which exists between "object Vptr" and "vptr point to Virtual table"(Section 4.2 for a complete discussion of virtual functions)
Look at the following scenario:
Bear B; Zooanimal za = b;        This will cause a cut (sliced)//Call Zooanimal::rotate () za.rotate ();
why does rotate () call a zooanimal entity instead of a bear entity? In addition, if the initialization function (when applied to the assignment operation above) copies an object content completely to another object, why does Za's vptr not point to the Bear's virtual table?
the answer to the second question is, the compiler makes a selection between initialization and assignment (Assignment) operations (Assigning a class object to another class object). The compiler must ensure that if an object contains one or more vptrs, the contents of those vptrs will not be initialized or changed by base class object.
As for the answer to the first question is: Za is not (and will never be) a bear, it is (and can only be) a zooanimal. The potential power of "more than one type" caused by polymorphism cannot actually be played in the "Direct Access Objects" thing. There is a specious notion that OO programs do not support direct processing of object. As shown below:
{    zooanimal za;    Zooanimal *pza;    Bear B;    Panda *pp = new Panda;    Pza = &b;}
It is clearly not a problem to assign the address of za or b, or the contents of PP (also an address) to Pza. A pointer or a reference supports polymorphism because they do not throw any "type-related memory delegate operations (Type-dependent Commitment)" in memory, and will be subject to changes in the knowledge of the memory they point to " Size and the way content is interpreted. "
However, if you change the size of object za, it will violate its definition of "resource demand" protected by the contract. If the entire Bear object is assigned to ZA, it will overflow the memory it has configured and the result will be faulted.
When a base class object is directly initialized (or assigned to) a derived class object, The derived object is cut (sliced) to plug into the smaller base type memory. Derived type will not leave any clues. Polymorphic then no longer present, and a strict compiler can parse a "virtual function call action triggered by this object" at compile time, thus avoiding the virtual mechanism, if virtual function is defined as inline, it is much more efficient.
In summary, polymorphism is a powerful design mechanism that allows for the encapsulation of related types after inheriting an abstract public interface. Library_materials system is one example. The price to pay is additional indirection-whether in "Memory acquisition" or "type judgment", C + + supports polymorphism through class pointers and references, a programming style called "Object-oriented" (object-oriented Model OO)).
C + + also supports Specific ADT program style, now known as object-based (OB). For example, a string class, a non-polymorphic data type, String class can show a non-polymorphic form of encapsulation: it provides a public interface and a private real work, including data and algorithms, but does not support the expansion of types. One ob design may be faster and more compact than a peer Oo design, the speed is because all function-throwing operations are resolved at compile time, the object is built without the need to set the virtual mechanism, the space is compact because each class object does not need to burden the traditional to support the virtual mechanism of the additional burden, However, OB design is less resilient.
there is often a trade-off between elasticity (OO) and efficiency (OB), and it is important to have a clear understanding of both the behavior and the needs of the application before you can effectively choose one.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

C + + object model----about objects

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.