[Previous] C ++ notes: Basics of Object-Oriented Programming
Convert and inherit from the derived class to the base class to automatically convert
Derived class pointer ----> base class Pointer --/-> derived class pointer
Derived class Object --/-> base class Object --/-> derived class Object
Reference or pointer of a derived class ObjectYesAutomatic conversionIsBase ClassA reference or pointer to a sub-object. (Because the derived class object is also a base class Object)
NoSlaveBase class reference or pointerToDerived classReferenced or pointerAutomatic conversion. (A base class object may or may not be part of a derived class Object)
- Although objects of the derived type can be used to initialize or assign values to objects of the base class type, the conversion of objects is more complex,
No derived type objectToBase ClassType objectDirect Conversion.
- Available
The address of the derived class Object assigns values or initializes pointers of the base class type.
- Available
A reference of a derived type or an object that initializes a reference of a base class type.
Conversion by reference is different from conversion object
- Pass the object to the desired audience
ReferenceThe reference is directly bound to the object. Although it seems that the object is being passed, the real parameter is actually a reference to the object, and the object itself is not copied, and the conversion does not change the derived type object in any way.The object is still a derived type object..
- Pass the derived class object to the expected receiving Base
Class Object(Rather than reference), the type of the form parameter is fixed, and the form parameter is a base class object at compile time and runtime. If you use a derived type object to call such a function,The base class of the derived class object is copied to the form parameter..
- One is
Conversion of a derived class object to a base class type reference, One is to useA derived class Object initializes or assigns a value to a base class object.To understand the differences between them.
Initialize or assign values to base class objects using a derived class Object
- Initializes or assigns values to base class objects. In fact, the constructor is called when the function is called: during initialization, and the value assignment operator is called when the value is assigned.
- There are two possibilities for initializing or assigning values to base class objects using a derived class object.
-
The base class explicitly defines the meaning of copying or assigning a derived type object to the base class object. However, this situation is not common. [Code1]
-
The base class generally (explicitly or implicitly) defines its own copy constructor and value assignment operator., These members accept a form parameter,The parameter is a const reference of the base class type.. Because there is a conversion from a derived class reference to a base class reference, these copy control members can be used to initialize or assign values to the base class object from the derived class object. [Code2]
- Convert a Bulk_item object to an Item_base reference, which only means to bind an Item_base reference to the Bulk_item object.
- Pass the reference as a real parameter to the copy constructor or value assignment operator.
- The operators use the Item_base part of Bulk_item to initialize or assign values to the members of the Item_base object that call the constructor or assign values respectively.
- Once the operator is executed, the object is Item_base. It contains a copy of the Item_base part of Bulk_item, but the Bulk_item part of the real parameter is ignored.
Conversion from a derived class to a base class to accessibility
- Like inherited member functions, conversion from a derived class to a base class may or may not be accessible. Conversion access depends on the access label specified in the derived list of the derived class.
- If it is a public inheritance, both the user code and the descendant class can use the conversion from the derived class to the base class.
- If the class is derived using private or protected inheritance, the user code cannot convert the derived type object to the base class object.
- For private inheritance, the classes derived from the private inheritance class cannot be converted to the base class.
- If it is protected inheritance, the subsequent members of the derived class can be converted to the base class type.
- To determine whether the conversion to the base class is accessible, consider
Whether the public Member of the base class accessesIf yes, the conversion is accessible. Otherwise, the conversion is not accessible.
- No matter what the derived access label is, the derived class itself can access the public members of the base class. Therefore, the members and friends of the derived class can always access the conversion from the derived class to the base class.
Details
Conversion from a derived class to a base class
- Slave
The automatic conversion from the base class to the derived class does not exist.
- The reason is that the base class object can only be a base class object and cannot contain members of the derived type. If the base class object is allowed to assign values to the derived type object, you can try to use the derived class object to access non-existent members.
Base Class pointer or referenceWhen actually bound to an object bound to a derived class, conversion from the base class to the derived class also has restrictions.
- During compilation, the compiler cannot know that a specific conversion is actually safe at runtime. The compiler determines whether the conversion is legal. Only the pointer or referenced static type is used.
- If
It is safe to switch from the base class to the derived class., You can usestatic_castForce the compiler to perform conversion. Alternatively, you can usedynamic_castApply to be executed at runtime.
Constructor and replication Control
- Each derived class object is defined by
A (non-static) member is composed of one or more base class sub-objects.This fact affects the construction, copying, assignment, and revocation of derived type objects.
- When constructing, copying, assigning, and revoking a derived class object,
It also constructs, copies, assigns, and revokes these base classes as sub-objects..
- Constructor and replication Control Members cannot inherit. Each class defines its own constructor and replication control members. If
If you do not define your own default constructor and replica control members, the merged version will be used..
- Only the special constructor used by the derived class is required. The base class should be defined as protected when the constructor is used.
Constructor of a derived class
Replication control and inheritance
- If the derived class explicitly defines its own copy constructor or value assignment operator, this definition will completely overwrite the default definition.
The copy constructor and value assignment operator of the inherited class are responsible for copying or assigning values to the base class components and their own members..
- If the derived class defines its own copy constructor, the copy constructor generally corresponds
Use base-class replication constructors explicitlyInitialize the Base class of the object. Otherwise, if the default constructor of the Base class is run, the newly constructed object will have a strange configuration: its Base part will save the default value, its Derived member is a copy of another object. [Code6]
- If the derived class defines its own
Value assignment operator, The operator must beThe base class is explicitly assigned a value.. [Code7]
- The work of the Destructor is different from that of the copy constructor and the value assignment operator,
The derived class destructor is not responsible for revoking the member of the base class object.
Class scope under Inheritance
- In the case of inheritance, the scope of the derived class is nested in the scope of the base class. If the name cannot be determined in the scope of the derived class, search for the definition of the name in the scope of the peripheral base class.
The static types of objects, references, or pointers determine the actions that an object can perform.
- When the static type and the dynamic type may be different, just as the reference or pointer of the base class type may occur, the static type still determines what Members can be used. [Code8]
- A derived class member with the same name as a base class member will block direct access to the base class member.
- You can use the scope operator to access the blocked base class members. For example:
Base::mem
- When designing a derived class, it is best to avoid conflicts with the names of base class members as long as possible.
- The base class and the derived class use the same name as the member function. In the scope of the derived class, the member will
SHIELD base class members.Even if the function prototype is differentThe base class members are also blocked. [Code9]
- The functions declared in the local scope do not reload the functions defined in the global scope. Similarly, the functions defined in the derived class do not reload the Members defined in the base class.
- When calling a function through a derived class object, the real parameter must match the version defined in the derived class. The base class function is considered only when the derived class does not define the function.
- A derived class can redefine zero or more inherited versions.
- If the derived class re-defines the overload member, the derived type is used.
You can only access the members that are defined in the derived class.
- If you want to use the overloaded version of the derived class, the derived class must either
Redefines all the overloaded versions, either or not.
- Sometimes a class only needs to redefine the behavior of some versions in a reload set, and wants to inherit the meaning of other versions, it can provide
Using statement
- A using statement
Only one name can be specified.Therefore, the using Declaration for the base class member function name willAdd all overloaded instances to the scope of the derived class. After all the names are added to the scope, the derived class only needs to redefine the functions that must be defined for this type. For other versions, the inherited functions can be used.
Container and inheritance
- You want to use containers (or built-in arrays) to save objects associated with inheritance. However, objects are not polymorphism. This fact affects the use of containers in the inheritance hierarchy. [Code10]
- If it is a base class container, the derived class will be truncated. If it is a derived class container, it cannot be placed in the base class.
- The only viable option is
Use a container to save the object pointer. However, the cost is that you need to manage objects and pointers. You must ensure that the objects to be directed exist as long as the container exists. If the object is dynamically allocated, you must ensure that the object is released properly when the container disappears.
CodeCode1: The base class explicitly defines the meaning of copying or assigning a derived type object to the 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: The base class generally (explicitly or implicitly) defines its own copy constructor and value assignment operator
Item_base item; // object of base typeBulk_item bulk; // object of derived type// ok: uses Item_base::Item_base(const Item_base&) constructorItem_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: Define the default constructor
class Bulk_item : public Item_base { public: Bulk_item(): min_qty(0), discount(0.0) { } // as before };
Code4: passing real parameters to the 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: use the default real parameters in the derived class Constructor
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}; // The default value is provided for each parameter. Therefore, the constructor can be used with 0 to 4 real parameters.
Code6: defines the copy constructor of the derived class. Generally, the base class part of the object should be initialized using the base class copy constructor explicitly.
Class Base {/*... */}; class Derived: public Base {public: // Base: Base (const Base &) not invoked automatically Derived (const Derived & d): Base (d) /* other member initialization */{/*... */};/* initialize the function Base (d) to convert the derived class Object d to its reference of the Base class, and call the Base class copy constructor. If the base class initialization function is omitted, run the following code: * // probably incorrect definition of the Derived copy constructorDerived (const Derived & d) /* derived member initizations */{/*... * //}/* The result is the Base class of the initialization object of the default constructor running the Base. Assuming that the initialization of the Derived member copies the corresponding member from d, the newly constructed object will have a strange configuration: its Base part will save the default value, its Derived member is a copy of another object. */
Code7: Value assignment operator of a 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 // do whatever needed to clean 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 in the left operand and assigns a new value from rhs. After the operator is executed, You need to assign values to the members in the derived class. */
Code8: Name Search occurs during compilation
/* For example, you can add a member to the Disc_item class. The member returns a pair object that saves the minimum (or maximum) quantity and discount price: */class Disc_item: public Item_base {public: std: pair <size_t, double> discount_policy () const {return std: make_pair (quantity, discount);} // other members as before }; /* access discount_policy: */Bulk_item bulk; Bulk_item * bulkP = & bulk; // OK: staticanddynamictypesarethe sameItem_base * itemP = & bulk; // OK: static and dynamic types differ bulkP-> discount_policy (); // OK: bulkP has type Bulk_item * itemP-> discount_policy (); // error: itemP has type Item_base */* It is wrong to redefine the access to itemP, because the base class type pointer (reference or object) can only access the base class part of the object, the discount_policy member is not defined in the base class. */
Code9: scope 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: callbase: memfcnd. memfcn (10); // callbase: memfcnd. memfcn (); // callderived: memfcnd. base: memfcn (); // error: memfcn with no arguments is hidden/* the third call may be strange: d. memfcn (); // error: Derived has no memfcn that takes no arguments In the ived class. Once the name is found, the compiler will not continue searching. This call does not match the memfcn definition in Derived. This definition wants to accept int real parameters, and this function call does not provide such real parameters, so an error occurs. */
From:
Http://blog.csdn.net/liufei_learning/article/details/22364861