C + + Notes: Object Oriented Programming advanced __linux

Source: Internet
Author: User
Tags class operator
[Previous Article] C + + Notes: Object Oriented Programming Basics
Conversion and Inheritance derived class to base class to auto convert

Derived class pointers----> base class pointers--/-> derived class pointers
A derived class object--/-> a base class object--/-> a reference or pointer to a derived class object that can be automatically converted to a reference or pointer to a base class child object. (because a derived class object is also a base class object) does not have an automatic conversion from a base class reference or from a pointer to a derived class reference or pointer. (A base class object may or may not be part of a derived class object) although it is generally possible to initialize or assign an object of a base class type using an object of a derived type, the situation of the object transformation is more complex and there is no direct conversion from the derived type object to the base class type object. You can use the address of a derived class object to assign or initialize a pointer to a base class type. You can use a reference to a derived type or an object to initialize a reference to a base class type. Reference conversions are different than when a transformation object passes an object to a function that expects to accept a reference. A reference is directly bound to the object, although it appears to be passing the object, actually the argument is a reference to the object, the object itself is not replicated, and the transformation does not change the derived type object in any way, which is still a derived type object. When you pass a derived class object to a function that you want to accept a base class type Object instead of a reference, the type of the formal parameter is fixed, and both compile-time and Run-time parameters are base class type objects. If such a function is invoked with a derived type object, the base class part of the derived class object is copied to the formal parameter. It is important to understand the difference between a derived class object being converted to a base class type reference, and one that initializes or assigns a base class object with a derived class object. Initializes or assigns a base class object to a base class object, using a derived class object to initialize or assign a value to it. It is actually called when the constructor is called when the function is initialized, when the assignment operator is called to initialize or assign to the base class object with the derived class object, there are two possibilities.

The base class explicitly defines the meaning of copying or assigning a derived type object to a base class object, but this is not uncommon. [Code1]

The base class generally (explicitly or implicitly) defines its own copy constructors and assignment operators, which accept a formal parameter that is a const reference to the base class type. Because there is a conversion from a derived class reference to a base class reference, these replication control members can be used to initialize or assign the base class object from the derived class object. [Code2] Converts a Bulk_item object to a item_base reference, which simply means that a item_base reference is bound to a Bulk_item object. Pass the reference as an argument to the copy constructor or assignment operator. Those operators initialize or assign values to the members of the Item_base object that called the constructor or assignment, using the item_base part of the Bulk_item. Once the operator completes, the object is item_base. It contains a copy of the item_base portion of the Bulk_item, but the bulk_item part of the argument is ignored.derived classes to the base class to be converted to accessibilityAs with inherited member functions, conversions from derived classes to base classes may or may not be accessible. Whether the conversion is accessed depends on the access label specified in the derived list of the derived class. If it is public inheritance, both user code and descendant classes can use the conversion from the derived class to the base class. If a class is derived by using private or protected inheritance, user code cannot convert a derived type object to a base class object. In the case of private inheritance, a class derived from a private inheriting class cannot be converted to a base class. In the case of protected inheritance, members of subsequent derived classes can be converted to base class types. To determine whether a conversion to a base class is accessible, you can consider whether the public member of the base class is accessible and, if so, the conversion is inaccessible. Regardless of the derived access label, the derived class itself can access the public members of the base class, so the members and friends of the derived class itself can always access the conversion of the derived class to the base class.
Detailedconversion of derived class to base classAutomatic conversion from a base class to a derived class does not exist because the base class object can only be a base class object and it cannot contain derived type members. If you allow a derived type object to be assigned a value with a base class object, you can attempt to access a nonexistent member by using the derived class object. When a base class pointer or reference is actually bound to a derived class object, the conversion from the base class to the derived class also exists to limit the compiler's inability to know at compile time that a particular transformation is actually safe at run time. The compiler determines whether the conversion is legitimate, looking only at the pointer or the static type of the reference if you know that the conversion from the base class to the derived class is safe, you can use static_cast to force the compiler to convert. Alternatively, you can use dynamic_cast to apply at run time.Constructors and replication controlThe fact that each derived class object consists of a (non-static) member defined in a derived class, plus one or more base class child objects, affects the construction, copying, assignment, and revocation of derived type objects. When you construct, copy, assign, and undo derived class objects, you also construct, copy, assign, and revoke the base classes as child objects. Constructors and replication control members cannot inherit, and each class defines its own constructors and replication control members. If a class does not define its own default constructor and copy control members, the composite version is used. Only special constructors that you want the derived class to use, the base class when the constructor should be defined as protected.constructors for derived classes

Composite derived class default constructor derived class A composite default constructor differs from a non derived constructor in that it initializes the base class portion of a derived class object in addition to the data member of the derived class. The base class part is initialized by the default constructor of the base class. For the Bulk_item class, the resultant default constructor does this: invokes the default constructor of the Item_base, initializes the ISBN member to an empty string, and initializes the price member to 0. Initializes a member of the Bulk_item with a regular variable initialization rule, that is, the Qty and discount members are uninitialized.

Defines the base class portion of the default constructor initialization object for the implicit invocation of item_base in the default constructor [Code3] Code3, and then initializes the members of the Bulk_item section and executes the function body of the constructor. The basis function class constructor passes the argument [Code4] constructor initialization list, which provides an initial value for the class's base class and members, and does not specify the order in which the initialization is performed. Initializes the base class, and then initializes the members of the derived class according to the declaration order. Use the default argument in a derived class constructor. [CODE5] can only initialize a direct base classreplication control and inheritanceIf a derived class explicitly defines its own copy constructor or assignment operator, the definition will completely override the default definition. The copy constructors and assignment operators of the inherited class are responsible for copying or assigning the base class composition and the members of the class themselves. If the derived class defines its own copy constructor, the copy constructor should typically explicitly use the base class copy constructor to initialize the base class portion of the object, otherwise the default constructor for the base class will have a strange configuration: its base portion will hold the default value, and its A derived member is a copy of another object. [Code6] If a derived class defines its own assignment operator, the operator must explicitly assign the base class part. The work of the [Code7] destructor differs from the copy constructor and assignment operator, and the derived class destructor is not responsible for revoking the members of the base class object.class scope under inheritanceIn the case of inheritance, the scope of the derived class is nested within the base class scope. If you cannot determine a name in the scope of a derived class, look for the definition of that name in the scope of the perimeter base class.  The static type of an object, reference, or pointer determines the behavior that an object can complete. Static types still determine what members can be used when static types and dynamic types may be different, as can occur when a reference or pointer to a base class type is used. [Code8] derived class members with the same name as the base class member will mask direct access to the base class members. You can use the scope operator to access a masked base class member, for example: Base::mem when designing a derived class, it is best to avoid conflicts with the names of base class members whenever possible. A member function of the same name is used in the base class and derived classes, and derived class members will mask the base class members in the derived class scope. Base class members are masked even if the function prototypes are different. A function declared in a [Code9] local scope does not overload a function defined in the global scope, nor does the function defined in the derived class overload the members defined in the base class. When you call a function from a derived class object, the argument must match the version defined in the derived class, and the base class function is considered only when the derived class does not define the function at all. A derived class can redefine 0 or more versions that are inherited. If a derived class has redefined an overloaded member, only those members that are redefined in the derived class can be accessed through the derived type. If a derived class wants to use an overloaded version of its own type, the derived class must either redefine all overloaded versions, or neither. Sometimes a class needs to redefine the behavior of only some versions of an overloaded set, and to inherit the meaning of other versions, you can provide the overloaded member with a using declaration that only one name can be specified, and the formal parameter list cannot be specified. A using declaration for a base class member function name adds all the overloaded instances of the function to the scope of the derived class. After all the names have been added to the scope, the derived class only needs to redefine those functions that this type does have to define, and you can use the inherited definition for other versions.Containers and InheritanceYou want to use a container (or built-in array) to save objects associated with inheritance. However, the fact that the object is not polymorphic has an effect on the type used to use the container in the inheritance hierarchy. [Code10] If the base class container then the derived class is truncated, if the derived class container cannot put into the base class the only viable option might be to use the container to hold the object's pointer. But the price is the need for users to face the problem of management objects and pointers, the user must ensure that as long as the container exists, the object is pointed to exist. If the object is dynamically allocated, the user must ensure that the object is disposed appropriately when the container disappears.Code Code1: base class explicitly defines the meaning of copying or assigning a derived type object to a base class object

Class Derived;
 Class Base {public
 :
     base (const derived&);  Create a new base from a Derived
     base &operator= (const derived&);  Assign from a Derived
     //...
 };

Code2: base classes typically (explicitly or implicitly) define their own copy constructors and assignment operators
Item_base item; Object of base type
Bulk_item Bulk//object of derived type
//ok:uses item_base::item_base (const Item_bas e&) Constructor
item_base Item (bulk);  Bulk is ' sliced down ' to its item_base portion
//ok:calls item_base::operator= (const item_base&)
Item = Bulk;           Bulk is ' sliced down ' to its item_base portion

Code3: Defining a default constructor
Class Bulk_item:public Item_base {public
 :
     bulk_item (): Min_qty (0), Discount (0.0) {}
     //As before
 };

Code4: Passing arguments to a base class constructor
Class Bulk_item:public Item_base {public
 :
     bulk_item (const std::string& book, double sales_price,
               std :: size_t qty = 0, double disc_rate = 0.0):
                  item_base (book, Sales_price),
                  min_qty (qty), Discount (disc_rate) {}
  //as before
  };

CODE5: Using default arguments in derived class constructors
Class Bulk_item:public Item_base {public
 :
     bulk_item (const std::string& book = "", double sales_price = 0.0 ,
               std::size_t qty = 0, double disc_rate = 0.0):
                  item_base (book, Sales_price), Min_qty (
                  qty), Discount ( disc_rate) {}
     //As before
  };
This provides a default value for each parameter, so you can use the constructor with 0 to 4 arguments.

Code6: Defines a copy constructor for a derived class, which should typically explicitly use the base class copy constructor to initialize the base class part of an object
Class Base {/* ... */};
 Class Derived:public Base {public
 :
     //Base::base (const base&) not invoked automatically Derived
     (const derived& d):
          Base (d)/* Other Member Initialization * *//{/* ... */}
};
/* Initialization function base (d) converts a derived class object D to a reference to its base class part and calls the base class copy constructor. If you omit the base class initialization function, the following code: *
//Probably incorrect definition of the Derived copy constructor
Derived (const derived& d * * Derived member Initizations * * * * *
effect is the base class portion of the default constructor initialization object that runs base. Assuming that the initialization of the Derived member from D copies the corresponding member, the newly constructed object will have a strange configuration: its Base portion holds the default value, and its Derived member is a copy of another object. */

Code7: assignment operator for derived class
base::operator= (const base&) not invoked automatically
 Derived &derived::operator= (const Derived & RHS)
 {
    if (this!= &rhs) {
    base::operator= (RHS);//assigns the Base part
    /Does whatever needed to CLE An up the "old" value in the derived part//Assign the "members" from the
    derived
    }
    retrun *this;
The/* base class operator releases the value of the base class portion of the left-hand operand and assigns a new value from the RHS. After the operator completes, the next thing to do is to assign a value to the member in the derived class. */

Code8: Name lookup occurs at compile time
/* For example, you can add a member to the Disc_item class that returns a pair object that holds the minimum (or maximum) quantity and discount Price: */
 class disc_item:public Item_base {public
 :
     std::p air<size_t, double> discount_policy () const
         {return Std::make_pair (quantity, discount);}
     Other members as before
 };
/* The discount_policy:*/Bulk_item Bulk can only be accessed through an object, pointer, or reference of the Disc_item type or disc_item derived type
 ;
bulk_item*bulkp=&bulk; Ok:staticanddynamictypesarethe same
item_base *itemp = &bulk;//ok:static and dynamic types differ 
->discount_policy (); OK:BULKP has type bulk_item* 
itemp->discount_policy ();//Error:itemp has type item_base*/
* Redefine itemp Access is incorrect because a pointer to a base class type (a reference or an object) can access only the base class portion of the object, and no Discount_policy members are defined in the base class. */

Code9: Scopes and member functions
struct Base {
     int memfcn ();
 };
 struct Derived:base {
     int memfcn (int);//Hides MEMFCN in the Base
 };
Derived D; Base b;
B.MEMFCN ();//Ok:calls BASE::MEMFCN
D.MEMFCN (a)//calls BASE::MEMFCN () D.MEMFCN calls
();
D.BASE::MEMFCN ();  ERROR:MEMFCN

with the no arguments is hidden///* May be strange is the third call:
D.MEMFCN ();//error:derived has no MEMFCN that T Akes no arguments
to determine this call, the compiler needs to find the name MEMFCN and find it in the Derived class. Once the name has been found, the compiler no longer continues to look for it. This call does not match the MEMFCN definition in Derived, which wants to accept the int argument, and the function call does not provide that argument, and therefore an error. */

From:
http://blog.csdn.net/liufei_learning/article/details/22364861

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.