Class Object Pointer and reference

Source: Internet
Author: User
It is important to use class object pointers and references, especially references, in terms of object-oriented programming and function parameter descriptions-especially the latter. Class objects may involve a considerable amount of data. Therefore, it is very time-consuming and inefficient to use the value-passing mechanism (specifying function parameters as objects) because each real parameter object needs to be copied. Some other technologies that are essential for some operations of the class also need to be referenced. As we will see later, if reference parameters are not used, we will not be able to write a copy constructor. Class Object PointerWe declare a pointer to a class object in the same way as other pointers. For example, the following statement declares a pointer to a cbox object: cbox * pbox = 0; // declare a pointer to cbox. Now, we can use the usual method in the value assignment statement, use this pointer to store the cbox object address: pbox = & cigar; // store address of cbox object cigar in pbox as in compare () when we use the this pointer in the definition of a member function, we can use the object pointer to call the function. For example, we can use the pointer pbox to call the volume (): cout <pbox-> volume (); // display volume of object pointed to by pbox this statement again uses the indirect member access operator. In this case, most programmers usually use this operator. Therefore, from now on, this book will also be widely used. Try: the pointer of the class object allows us to try to practice the usage of the indirect member access operator in a little deeper. We will use ex7_10.cpp as the basis, but some modifications are required. // Ex7_13.cpp // exercising the indirect member access operator # include <iostream> Using STD: cout; Using STD: Endl; Class cbox // class definition at global scope {public: // constructor definition cbox (double Lv = 1.0, double bv = 1.0, double HV = 1.0) {cout <Endl <"constructor called. "; m_length = lv; // set values of m_width = BV; // data members m_height = HV;} // function to calculate the V Olume of a box double volume () const {return m_length * m_width * m_height;} // function to compare two boxes which returns true (1) // if the first is greater that the second, and false (0) otherwise int compare (cbox * pbox) const {return this-> volume ()> pbox-> volume ();} PRIVATE: Double m_length; // length of a box in inches double m_width; // width of a box in inches double m_height; // height o F A box in inches}; int main () {cbox Boxes [5]; // array of cbox objects declared cbox match (2.2, 1.1, 0.5 ); // declare match box cbox cigar (8.0, 5.0, 1.0); // declare cigar box cbox * PB1 = & cigar; // initialize pointer to cigar object address cbox * master = 0; // pointer to cbox initialized to null cout <Endl <"Address of cigar is" <PB1 // display address <Endl <"volume of cigar is" <PB1 -> Volume (); // volume of object pointed to master = & match; If (master-> compare (PB1 )) // compare via pointers cout <Endl <"Match is greater than cigar"; else cout <Endl <"Match is less than or equal to cigar "; PB1 = boxes; // set to address of array Boxes [2] = match; // set 3rd element to match cout <Endl // now access thru pointer <"volume of boxes [2] is" <(PB1 + 2) -> volume (); cout <End L; return 0;} If you run this example, the output looks roughly the same as shown below: constructor called. constructor called. constructor called. constructor called. constructor called. constructor called. constructor called. address of cigar is 0012fe20volume of cigar is 40 match is less than or equal to cigarvolume of boxes [2] is 1.21 Note: of course, the cigar address value of the object on your PC may be different. ExampleModification to the class definition is not an important substantive modification. We just changed the compare () function to accept the pointer of the cbox object as the real parameter. In addition, we now know the information about the const member function, and because the compare () function does not modify the object, it is declared as Const. The main () function is only used in a variety of random ways to practice using cbox object pointers. In the main () function, we declare the pointers of two cbox objects after declaring arrays boxes, cbox objects cigar, and match. The first pointer PB1 is initialized to the cigar address of the object, and the second pointer is initialized to null. The two statements use pointers in exactly the same way as when we use pointers of basic types. The fact that we are using a pointer of a custom type makes no difference. We use the operator PB1 and indirect member access to obtain the volume of the object to be pointed to and display the result. Then, the address of the match is assigned to the master node of the master node. Because the real parameters of the compare () function are cbox object pointers, this function uses indirect member access operators when calling the volume () function for the real parameter object. To verify that address arithmetic can be executed when the pointer PB1 is used to select a member function, we set PB1 to the address of the first element in the cbox array boxes. Then, select the third element of the array and calculate its volume. The result is the same as that of match. From the output, we can see that there are seven calls to the cbox object constructor, five of which are the creation of array boxes, and the creation of the object cigar and match are required each time. In short, there is essentially no difference between a pointer using a class object and a pointer using a basic type (such as a double type. Class Object ReferenceWhen used together with the same type, the reference can truly obtain the honors it deserves. As with pointers, there is essentially no difference between declarations and references using class objects and references using basic type variables. For example, to declare the reference of the object cigar, we can write: cbox & rcigar = cigar; // Define reference to object cigar. In order to use the reference to calculate the volume of the object cigar, we only need to use the reference name where the object name should appear: cout <rcigar. volume (); // output volume of cigar thru a reference we may remember that the reference plays the role of the alias of the referenced object, so its usage is exactly the same as that of the original object name. 1. Implement the replication ConstructorThe importance of reference is actually reflected in the context of real parameters and return values of functions (especially member functions of classes. Let's first return to the copy constructor issue. At present, we have been avoiding the need to compile our own copy constructor for the moment, and are concentrated on how to compile a copy constructor. We will use the cbox class to make the discussion more specific. A copy constructor initializes an existing object of the same type to create a constructor for the new object. Therefore, similar objects must be accepted as real parameters. After consideration, we may write the following prototype: cbox (cbox initb); now, consider what will happen when calling this constructor. If we write cbox mybox = cigar; such a declaration statement, the following call to the replication constructor is generated: cbox (cigar ); this statement does not seem to have any problems before realizing that real parameters are passed by the value passing mechanism. Before the cigar object can be passed, the compiler must arrange to create a copy of the object. Therefore, the compiler needs to call the copy constructor to create a copy of the real parameter to process the statement used to copy the constructor. Unfortunately, because it is passed by value, the second call also needs to create a copy of the real parameter, so you have to call the copy constructor, so it will continue. What we finally get is an infinite call to the replication constructor. As you have already guessed, the solution is to use const to reference the form parameter. We can prototype the replication constructor as follows: cbox (const cbox & initb); now, the computer does not need to copy the real parameters of the replication constructor. The real parameter is used to initialize the reference parameter, so no replication occurs. As mentioned in the reference discussion above, if the function parameter is a reference, you do not need to copy the real parameter when calling the function. The function directly accesses the real variable in the called function. The const qualifier is used to ensure that the function cannot modify real parameters. Note: This is another important use of the const qualifier. We should always declare the referenced parameter of the function as const unless the function will modify the real parameter. We can implement the replication constructor as follows: cbox (const cbox & initb) {m_length = initb. m_length; m_width = initb. m_width; m_height = initb. m_height;} the definition of the replication constructor assumes that it is located outside the class definition, so the constructor name is limited by the class name and scope parsing operator. Each data member of the created object is initialized using the corresponding member of the real parameter object passed to the constructor. Of course, we can also use the initialization list to set the object value.

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.