C + + Primer (4th edition)-Study notes-Part 4: Object-oriented programming and generic programming

Source: Internet
Author: User
Tags define function function prototype

15th. Object-Oriented Programming OOP (Object-oriented programming)

Object-oriented programming is based on three basic concepts: Data Abstraction , inheritance , and dynamic binding 。 In C + +, you use classes for data abstraction, and class derivation to inherit from one class from another: Derived classes inherit members of the base class. Dynamic binding enables the compiler to decide at run time whether to use a function defined in a base class or a derived class
The function.
  1. Private members
    • The private member of the class cannot be accessed through the class object.
    • The private member of the base class cannot be accessed in a derived class.
    Private members are accessible only within the scope of the current class, and friends of the class can also access the private members of the class. For example, private members can be accessed in member functions, and private members of the class can also be accessed through the object of their class in the member function. The scope of a class includes: within the {} of the class definition, the function body of the member function outside the class definition, the parameter list, and so on.

  2. Protected members
    • Protected members cannot be accessed through class objects.
    protected members can be accessed by public derived classes (including derived classes of derived classes, passed down), meaning that the protected members of the base class can be used in derived classes.
    • Derived classes can access only the protected members of their base classes through derived class objects, and derived classes cannot access the protected members of their base class type objects.

  3. Derived classes and virtual functions
    Derived classes typically redefine inherited virtual functions. If a derived class does not redefine a virtual function, the version defined in the base class is used.
    In general, the declaration of a virtual function in a derived class must exactly match the way it is defined in the base class, with the exception of a virtual function that returns a reference (or pointer) to base type A. A virtual function in a derived class can return a reference (or pointer) to a derived class of Class A.
    Once a function is declared as a virtual function in the base class, it is always a virtual function, and the derived class cannot change the fact that the function is a virtual function. When you redefine a virtual function in a derived class, you can either use the virtual reserved word or do not use it.

  4. To determine the invocation of the virtual function at run time
    When a reference or pointer to a base class type is bound to a derived class object, when a virtual function is called, the function defined by the base class type is executed regardless of the type of the actual object, if the non-virtual function is called. If you call a virtual function , you will not be able to determine which function is called until run time, which is the version of the type definition of the object to which the reference is bound or the pointer is pointing. A virtual function is determined at run time only by a reference or a pointer call. Only in these cases will the dynamic type of the object be known until run time.

  5. Virtual functions and default arguments
    Virtual functions can also have default arguments. If a call omits an argument with a default value, the value used is defined by the type that called the function, regardless of the object's dynamic type. When a virtual function is called by a reference or pointer to a base class, the default argument is the value specified in the base class virtual function declaration, and if a virtual function is called by a pointer or reference to a derived class, the default argument is the value declared in the version of the derived class.

  6. Friend relationship and inheritance
    A friend relationship cannot inherit :
    (1) The friend of the base class has no special access rights to the members of the derived class.
    (2) A derived class of a friend class cannot access a class that grants a friend relationship.

  7. Inheritance vs. static members
    If the base class defines a static member, there is only one such member in the entire inheritance hierarchy. No matter how many derived classes derive from a base class, there is only one instance per static member.
    Static members follow general access control: If a member is private in the base class, the derived class cannot access it. If you can access members, you can access static members through the base class, or you can access static members through derived classes. In general, you can use either the scope operator or the point or arrow member to access the operator.

  8. Conversions from a derived class to a base class
    Pointers or References: (1) derived types reference to base class type references, (2) derived type pointers to base class type pointers. on the contrary, it is not possible.
    Objects: You can typically initialize or assign objects of a base class type to objects of a derived type, but there is no direct conversion from the derived type object to the base class type Object, and the compiler does not automatically convert the derived type object to the base class type
    Object.

  9. You can use a derived type object to assign or initialize a base class object.
    Pass an object of a derived type to a function that expects to accept a base class reference, which is actually a reference to the object, and the object itself is not copied.
    When you pass a derived class object to a function that expects to accept a base class type Object instead of a reference, the base class portion of the derived class object is copied to the parameter.

  10. Derived class constructors
    constructors and replication control members cannot inherit, each class defines its own constructors and replication control members. Like any class, a composite version is used if the class does not define its own default constructors and replication control members.
    The composition default constructor of a derived class, in addition to initializing the data members of the derived class, initializes the base class portion of the derived class object. The base class part is initialized by the default constructor of the base class.
    initialization list of derived class constructors can only initialize members of derived classes and cannot initialize inherited members directly。 A derived class constructor can indirectly initialize an inherited member only by including the base class in the constructor initialization list.
    Class Bulk_item:publicItem_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
    };
    The constructor initialization list provides the initial values for the class's base class and members, and it does not specify the order in which the initialization is performed. Initializes the base class first, and then initializes the members of the derived class according to the order in which they are declared.
    A class can only initialize its own direct base class(The base class is indirectly initialized by including the base class in the constructor initialization list).

  11. Replication Control and inheritance
    classes that contain only class types or built-in type data members, without pointers, can generally use composition operations, which do not require special control to copy, assign, or revoke such members. Classes with pointer members typically need to define their own replication controls to manage these members.

  12. derived class copy constructor

    Class Base {/* ... */};
    class derived:public  base
    {
    Public:
             derived (const derived& D): base strong> (d) {/* ... */}
    }; 

  13. Derived class assignment operators
    The assignment operator is typically similar to a copy constructor: If a derived class defines its own assignment operator, the operator must explicitly assign the base class part.
    base::operator= (const base&)
    Derived &derived::operator= (const Derived &RHS)
    {
    if (this = &RHS)//Prevent assigning yourself a value
    {
    base::operator= (RHS);// Call the assignment operator of the base class to assign a value to the base class part
    ...//Assign a value to a member of a derived class derived
    }
    return *this;
    }

  14. Derived class destructor
    The derived class destructor is not responsible for revoking the members of the base class object. Each destructor is only responsible for clearing its own members.
    Class Derived:public Base
    {
    Public
    ~derived () {/* takes
    */ }
    };
  15. Virtual destructor
    If the destructor of the base class in the hierarchy is a virtual function, the derived class destructor will also be a virtual function, and the derived class destructor is a virtual function, regardless of whether the derived class explicitly defines the destructor or uses a composition destructor.
    Recommendation: The root class of an inheritance hierarchy should also define a virtual destructor, even if the destructor does not work.

  16. Constructors and assignment operators are not virtual functions
    In a copy control member, only the destructor should be defined as a virtual function, and the constructor cannot be defined as a virtual function.

  17. Name Collisions and inheritance
    A member of a derived class with the same name as a base class member will mask direct access to the base class member.
    You can access a masked base class member by using the scope operator:
    struct Derived:base
    {
    int Get_base_mem () {return base::mem;}
    };
    When designing a derived class, it is best to avoid conflicts with the names of the base class members whenever possible.

  18. Scope and member functions
    A member function that uses the same name in a base class and a derived class behaves like a data member: A derived class member in a derived class scope masks a base class member. Base class members are masked even if the function prototype is different.

  19. Overloaded functions
    If a derived class redefined an overloaded member, only those members that are redefined in the derived class are accessible through derived types.
    If a derived class wants to use an overloaded version by its own type, the derived class must redefine all overloaded versions, but this is cumbersome and can be simplified by providing a using declaration to the overloaded members.
    Using base::func;//Note that the Func function in all base class base is visible in this class.

  20. Name Lookup and inheritance
    (1) First determine the static type of the object, reference, or pointer that made the function call.
    (2) Find the function in this class, if it is not found, find it in the direct base class, so follow the inheritance chain of the class and look up until the function is found or the last class is searched. If the name cannot be found in the class or its associated base class, the call is incorrect.
    (3) Once the name has been found, a regular type check is performed to see if the function call is legitimate given the found definition.
    (4) Assuming the function call is legitimate, the compiler generates code. If the function is a virtual function and is called through a reference or a pointer, the compiler generates code to determine which version of the function is run based on the object's dynamic type, otherwise the compiler generates code to call the function directly.

  21. Pure virtual function
    Write = 0 after the function parameter list to specify a pure virtual function . This function provides an interface that can be overridden for descendant types, but the version in this class is never called.
    Classes that contain (or inherit) one or more pure virtual functions are abstract base classes . You cannot create an object of an abstract type except as part of an object that is a derived class of an abstract base class.

16th Chapter templates and generics programming
Generic programming is to write code in a way that is independent of any particular type. Templates are the basis for generic programming. In generic programming, we write classes and functions that can be used polymorphic to span types that are not relevant at compile time. A class or a function can be used to manipulate multiple types of objects.
  1. The
  2. define function template
    function template is a type-independent function that can be used as a way to produce a specific type version of a function. Here is the template version of compare:
         //implement strcmp-like generic compare function
         //Retu RNs 0 if the values are equal, 1 if V1 is larger, 1 if V1 is smaller
         template < typename  t ;
         int Compare ( Const t  &v1, Const t  &v2)
         {
             if (V1 < v2) return-1;
             if (V2 < v1) return 1;
             return 0;
        &NBSP;} The
    template definition starts with the keyword template, followed by the template parameter list, which is a comma-delimited table of one or more template parameters that are enclosed in angle brackets.

  3. inline function templates
    Function templates can be declared inline in the same way as non-template functions. Specifiers cannot be placed before the keyword template until after it has been placed in the profile parameter list and before the return type.
    Template <typename t> inline T min (const t&, const t&);//ok:inline specifier follows template par Ameter List
    Inline template <typename t> T min (const t&, const t&);//error:incorrect placement of inline specifier

  4. Class template
    A class template is a class definition that defines a set of classes of a specific type, which is defined by using the template keyword followed by a list of angle brackets <> enclosed, comma-delimited lists of one or more template parameters.
    Template <class type> class Queue {
    Public
    Queue (); Default constructor
    Type &front (); return element from head of the Queue
    Const TYPE &front () const;
    void push (const Type &); add element to the back of the Queue
    void Pop (); remove element from head of Queue
    BOOL empty () const; True if no elements in the Queue
    Private
    // ...
    };
    In contrast to calling a function template, when you use a class template, you must explicitly specify an argument for the template parameter:
    Queue<int> Qi; Queue that holds ints
    queue< vector<double> > QC; Queue that holds vectors of doubles
    Queue<string> QS; Queue that holds strings

  5. Template parameters
    Template parameter scope: The name of a template parameter can be used at the end of a template declaration or definition until it is declared as a template parameter.
    Template parameters follow the regular name masking rules. A template that has the same name as the object, function, or type declared in the global scope is masked by the global name.

  6. Limit
    The name of the template parameter cannot be reused inside the template.
    The name of a template parameter can only be used once in the same template parameter list.
    The names of template parameters can be reused in different templates.

  7. Template declaration
    Like any other function or class, a template can be declared but not defined.
    The name of the template parameter can be different in the declaration and definition of the same template.

  8. Template type parameter
    Type parameters are made up of the keyword class or typename followed by specifiers. In the template parameter list, the two keywords have the same meaning, indicating that the name that follows is a type.
    It can be used to specify the return type or function parameter type, as well as for variable declarations or coercion of type conversions in the body of a function.

  9. The difference between TypeName and class
    In the function template parameter list, the keyword TypeName and class have the same meaning, can be used interchangeably, and two keywords can be used in the same template parameter list.
    The keyword TypeName is added to C + + as part of standard C + +, so older programs are more likely to use the keyword class only.

  10. Specifying a type within a template definition
    By prefixing the member name with the keyword typename, you can tell the compiler to treat the member as a type.
    Template <class Parm, class u>
    Parm FCN (parm* array, U value)
    {
    TypeName Parm::size_type * p; Ok:declares p to be a pointer
    }

  11. Non-type template parameters
    Template parameters do not have to be types.
    Template <class T, size_t n>
    void Array_init (T (&parm) [N])
    {
    for (size_t i = 0; I! = N; ++i) {
    Parm[i] = 0;
    }
    }

  12. Writing generic Programs
    The actions done inside the function template limit the types that can be used to instantiate the function. Therefore, it should be ensured that the type being used as a function argument actually supports any operation that is used, and that those operations are working properly in an environment where the template uses the actions.
    When writing template code, it is important to note that the requirements for the actual parameter types are as few as possible.

  13. Two important principles for writing generic code (with as few requirements as possible for an argument type):
    • The template's formal parameter is a const reference.
    • The tests in the function body are only used for < comparisons.

  14. Instantiation of a class
    Each instantiation of a class template results in a separate class type.
    To use a class template, you must explicitly specify a template argument.

  15. function template instantiation
    When using a function template, the compiler usually infers the template arguments for us.

  16. The compiler will only perform two conversions for the limited conversion of the arguments of the type parameter:
    Const Conversion: A function that accepts a const reference or a const pointer can be called by a reference or a pointer to a non-const object, without creating a new instantiation.
    • Array or function-to-pointer conversions: If a template parameter is not a reference type, an argument to the type of the set or function is applied to the regular pointer conversion.

  17. Class definitions and function declarations are placed in the header file, and function definitions and member definitions are placed in the source file.

  18. Include compilation model
    In the include compilation model, the compiler must see the definition of all the templates used. In general, you can make the definition available by adding a #include in the header file that declares the function template or class template, which introduces the source file that contains the related definitions.

  19. Compiling the model separately
    In the separate compilation model, the compiler will track the relevant template definitions for us. However, we have to let the compiler remember the given template definition, and you can use the Export keyword to do it.
    In a program, a template can be defined only once for export.
    (1) Function template
    In the definition of the function template, indicate that the function template is exported and include the Export keyword before the keyword template:
    Export Template <typename type>
    Type sum (type T1, type t2)/* ... */
    The declaration of this function template should be placed in the header file as usual, declaring that you do not have to specify export.
    (2) class template
    The class declaration must be placed in the header file, the class definition body in the header file should not use the keyword export, and export should be used in the class's implementation file.
    Template <class type> class Queue {...};
    Export Template <class type> class Queue;
    #include "Queue.h"
  20. Typically, when you use the name of a class template, you must specify a template parameter. There is an exception to this rule: the unqualified name of the class template can be used within the scope of the class itself. For example, in the declaration of the default constructor and the copy constructor, the name Queue is the queue<type> abbreviation.
    The compiler does not make such inferences for the template parameters of other templates used in the class, so you must specify a type parameter when declaring a pointer to the partner class Queueitem: Queueitem<type> *head; Pointer to first element in Queue

  21. Class template member functions
    • The template parameter list for the class must be followed by the keyword "stencil" switch.
    • You must indicate which class it is a member of.
    • The class name must contain its template parameters. For example:
    Template <class type> void queue<type>::d Estroy ()
    {
    while (!empty ())
    Pop ();
    }

  22. To set a class template as Friend
    Template <class type> class Queue;
    Template <class type> class Queueitem {
    Friend Class queue<type>;
    // ...
    };
    This declaration establishes the need for one-to-two mappings, which will only be instantiated with the same type as the Queueitem class
    The Queue class is set to friend.

  23. Set a function template as Friend
    Template <class t>
    std::ostream& operator<< (std::ostream&, const queue<t>&);
    Template <class type> class Queueitem {
    Friend Class queue<type>;
    Needs access to item and next
    Friend std::ostream&
    operator<< <Type> (std::ostream&, const queue<type>&);
    // ...
    };
    Template <class type> class Queue {
    Needs access to head
    Friend std::ostream&
    operator<< <Type> (std::ostream&, const queue<type>&);
    };

  24. Member templates
    Any class (template or non-template) can have itself as a member of a class template or function template, a member of which is called a member template, and the member template cannot be virtual.

  25. Defining member templates outside of a class
    When a member template is a member of a class template, its definition must include the class template parameters and its own template parameters. The first is the class template formal parameter list, followed by the member's own template parameter list.
    Template <class t> templates <class iter>// First templated parameter list Template<class t> is a class template, the second template parameter list Templat The E<class iter> is a member template.
    void Queue<t>::assign (ITER Beg, ITER end)
    {
    Destroy (); Remove existing elements in the This Queue
    Copy_elems (Beg, end); Copy elements from the input range
    }

  26. Static members of class templates
    Class templates can declare static members like any other class

C + + Primer (4th edition)-Study notes-Part 4: Object-oriented programming and generic programming

Related Article

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.