C ++ class and object details, object details

Source: Internet
Author: User

C ++ class and object details, object details

      • 1. What is a class?
        • 1-1 Development of Program Design
        • 1-2 process-oriented to object-oriented
        • 1-3 class definitions
        • 1-4 constructor destructor
      • 2. Memory Management
        • 2-1 Memory Distribution
        • 2-2 heap and stack
          • Difference between 2-2-1 heap and stack
          • 2-2-2 new and delete
      • Three-copy constructor
      • Combination of four types
        • 4-1 What is a combination of Classes
        • 4-2 Constructor
      • Inheritance 5
        • 5-1 Inheritance and Derivation
        • 5-2 constructor destructor during inheritance
        • 5-3 override the parent class Method
      • Six polymorphism and virtual functions
        • 6-1 What is polymorphism
        • 6-2 virtual functions
        • 6-3 pure virtual functions and abstract classes

1. What is the development of Class 1-1 programming?

Zookeeper we know that the development of the program has gone through three phases:Machine-oriented programming, process-oriented (structure) programming, and object-oriented programming. Machine-Oriented Programming mainly uses binary commands or assembly languages for programming. This method is easy to understand for computers, but it is very painful for programmers. It is generally difficult to understand or design without special training personnel, therefore, a process-oriented design method has been developed.
Zookeeper is similar to the process-oriented method that we normally think about. For example, we need to wash our clothes and design the program according to our operation steps:Remove clothes-> pour water and wash detergent-> Start rubbing-> dry clothesAnd then write functions in each step to simulate the implementation. The Representative language we use is the C language. It is true that this method facilitates programming to a great extent. However, as we develop, we need to describe more and more complex processes, and the project is getting bigger and bigger, when we start a new project, we often need to write code from the beginning. For example, we have a program to wash the coat and a program to wash the trousers, but since the Code is not reused or shared, as a result, we must start writing a program again. How can we enhance code reusability, flexibility, and scalability?
The proposal of the new issue of zookeeper leads to our Object-Oriented Programming (OOP), which is a computer programming architecture, one basic principle is that a program is composed of a single unit or object that can act as a subroutine. In this way, for the overall operation, each object can receive information, process data, and send information to other objects. Each unit can be applied to other programs. In this way, OOP achieves three main objectives of Software Engineering:Reusability, flexibility, and scalabilityThis represents our C ++ language. Of course, the C ++ language is compatible with the process-oriented language.

1-2 process-oriented to object-oriented

How does Zookeeper's object-oriented design implement code reuse and expansion? We know that in our process-oriented approach, we often do this:

1. design the corresponding data structure for the required functions 2. design the algorithm to complete this function

During this time, our program structure is as follows:Program = Algorithm + Data Structure. Therefore, when faced with a new problem, we often need to re-design the corresponding data structure and re-design the algorithm to complete this function. In this way, code reusability is relatively low.
When we design a program in an object-oriented way, we often think like this:

1. What are the sub-objects of this entire object? 2. What are the attributes and functions of each sub-object? 3. How are these sub-objects associated?

The Code designed by zookeeper is as follows:Object = Algorithm + data structure; program = Object + ·······
Because of the various objects that have completed sub-functions, it is easy to reuse code.
Objects are the basis of object-oriented objects, and classes are the basis for implementing these objects. Class describes a group of objects with the same features and behavior.

1-3 class definitions

In C ++ programs, we often separate the class definition from the member function definition to facilitate reading and coding.

1. The class definition can be viewed as an external interface of the class, which is generally written as a. h file. 2. The class member function definition can be viewed as an internal implementation of the class, and is generally written as a. cpp file.

In the code, we generally define a class as follows:

The following format is generally used for defining member functions of a class:

Return Value Class Name: function name (parameter list) {function body}

When the function is notClass Name ::The compiler will think that this is a common function, because we have not explained which class this function is, and it also shows the scope of this function, in the class scope, A member function of a class has unlimited access permissions to data members of the same class.
Zookeeper sets different access permissions for different members of the class to encapsulate the class, which enhances security and simplifies programming. users do not have to understand the specific implementation details, instead, you only need to use tired members with specific access permissions through external interfaces.

1-4 constructor and destructor

The aggregate functions constructor is a very important function in the class. It is mainly used to create and initialize objects. The constructor is automatically called by the system when an object is created. The constructor has the same name as the class and has no returned value. By default, the constructor has no parameter format. The constructor is generally in the following format:

Class name {public: class Name ();}

Note: The constructor does not have any parameters by default, but it can be reloaded, that is, we can set the constructor with parameters.
The aggregate functions constructor has three functions:

1. Allocate space, that is, classify the space used by the object in the memory. 2. Construct the structure and structure of the entire class. 3. initialize, that is, initialize the attributes in the class.

The opposite of the constructor is our destructor. The Destructor mainly cleans up objects before they are deleted and is automatically called at the end of the object lifecycle, then release the object space. Add the Destructor before the class name ~, No return value, no parameter, different from the constructor,The Destructor cannot be reconstructed.. The general form of destructor is as follows:

Class name {public ~ Class Name ();}
2. Memory Management 2-1 Memory Distribution

After the class is constructed, the system creates a space in the memory to store various types of data. After the class lifecycle ends, the system calls the destructor to recycle the space, our classes include constants, variables, and functions. How is the data stored in the memory?
Memory of the   C ++ program is generally divided into four areas,

Zookeeper should pay attention to the following:Data collection in the heap and stack is different. If the heap memory is allocated, it is the responsibility to recycle the data. Otherwise, memory leakage may occur, and the local variables allocated in the stack area in the function, space is automatically reclaimed and released at the end of the function.

2-2 heap and stack 2-2-1 heap and stack difference

Zookeeper divides the memory areas into stacks for convenient storage. The two have different features to store different data.
Zookeeper generally compares the heap space with other memory space, so it will bring a lot of freedom to the program to allocate space. However, this does not mean that the heap memory can be applied at will. Generally, there are several scenarios where the heap space is used:

-You will not be able to know how much object space is needed until the runtime.-You do not know how long the object's lifecycle is.-You will not know how much memory space is required for an object until the runtime.

Different from the heap, when creating a program, the compiler accurately keeps all the data length and time in the stack. Due to the FILO feature of the stack, when the stack pointer moves down, a new memory will be created, and the move up will release the corresponding space. Therefore, data in the stack can be accurately operated.
The following is an example of zookeeper:

2-2-2 new and delete

  Malloc and free are C ++/C standard library functions, and new/delete are C ++ operators. Note:One is a library function and the other is an operator..; What are the differences between the two? For library functions, when allocating heap memory, they do not care about what the object is, but only about how much space needs to be allocated. for operators, the memory size is related to the class object during the allocation, and the class constructor is called back when the memory is allocated.
They are all used to apply for dynamic memory and release the memory. Since new is used to apply for memory and the constructor can have parameters, the class type following new can also have parameters, in the following format:

Class name * variable name = new Class Name (·); Class Name * variable name = new class name [number of elements];

Struct we found that we can apply for an array of class objects, but note thatWhen allocating arrays of class objects from the heap, you can only call Default constructors without parameters, but cannot call constructors with parameters. Once no default constructor in the class is available, class arrays cannot be allocated.
As mentioned above, the memory space applied in the heap must be manually recycled. Therefore, the delete function is used to release the space and the class destructor will be called. The format is as follows:

Delete variable name; or delete [] variable name; variable name = null
Iii. copy constructors

A copy constructor is a special constructor. Its form parameter is an object reference of this class. In essence, one object is used to construct another object, or another object value is used to initialize a new constructed object. The format is as follows:

Class name {public class name (shape parameter) // constructor public class name (class Name & Object Name) // copy constructor} // copy constructor implementation class Name:: Class Name (Class Name & Object Name) {function body}

Zookeeper provides an example:

The above example shows an interesting phenomenon:In the copy constructor, we directly access the private member (pt. m_mx) in the class. In other cases, we cannot use "." for access.
The copy constructor has the following features:

-If the program does not declare a copy constructor for the class, the compiler generates a default copy constructor.-The default copy constructor execution function is, copy each data member value in the initial object to the newly created object. In the default copy constructor, the copy policy is to copy members one by one.

Because the copy constructor transfers the objects of this class, a problem occurs.
When the class constructor allocates a resource on the stack, it is common to assign a value to the string, while the copy constructor replicates resources. If it is just a simple copy, this will cause two objects to have one resource at the same time. When one object releases the resource and the other object is used again, the problem may occur.

How can this problem be solved by zookeeper? Obviously, the copy constructor cannot simply copy the resource. You need to manually write the copy constructor. The default copy constructor cannot be used. You need to copy the resource when copying the resource, so that the two objects will point to different resources.This is the difference between shallow copy and deep copy.
The copy constructor of zookeeper is often used in the following scenarios:

-When another object of the class is initialized with an object of the Class-if the function parameter is a class object, when calling the function, the real parameter is assigned to the form parameter, the system automatically calls the copy constructor-when the return value of the function is a class object, the system automatically calls the copy constructor.

Iv. Combination of Classes 4-1 What is a combination of Classes

What is a combination of classes? Simply put, a combination of classes means that the member data of classes is the object of another class. In this way, more complex abstraction can be implemented based on the existing abstraction.

4-2 Constructor

When our classes are combined, how does one initialize the classes? In general, it is not only responsible for the initial assignment of type members in this class, but also for the initialization of object members. The Declaration format is as follows:

Class Name: Class Name (the parameter required by the object member, the parameter of the class member): Object 1 (parameter), object 2 (parameter) {class initialization}

The following is an example of zookeeper:

When classes are combined, a new problem occurs. We know that every class has constructor and destructor. When classes are combined, what is the call sequence of constructor and destructor?

1. the call sequence of the constructor 1. call the constructor of the embedded object (according to the Declaration Order of the embedded object, which is constructed first by the speaker) 2. call this class constructor 2. the Calling sequence of destructor 1. call this type of destructor 2. call the destructor of the embedded object (according to the Declaration Order of the embedded object, first declare the first destructor)

  It should be noted that if the default constructor is called, the initialization of the embedded object will also call the default constructor.

5. Inheritance 5-1 Inheritance and Derivation

Since zookeeper is object-oriented and our display world is an object world, we should also describe the relationships between objects in the real world, such as inheritance, to describe the relationship between these types, the concept of inheritance is also introduced in C ++.
Zookeeper inheritance is an important mechanism in C ++. This mechanism automatically provides a class with operations and data structures from another class, this allows us to create a new class by defining existing components that do not exist in the new class. Inheritance is for code reuse and expansion.
Zookeeper inherits the following general definition formats:

Class derived class: public parent class {class Implementation}

Because the members of a class have different access permissions, class inheritance also has different inheritance methods (generally, class inheritance includes public inheritance, protection inheritance, and private inheritance ), after a class is inherited, it should have different access permissions. Different derivation conditions and the access permissions of class members are as follows:

5-2 constructor and destructor during inheritance

Since the members of the base class can be inherited, what about some special functions of the base class?
The constructor of the primitive class is not inherited. The derived class is a self-defined constructor. However, during the constructor, you only need to initialize new members in the class, initialize inherited base class members, and automatically call the constructor of the base class.
The constructor form of a derived class is as follows:

Derived class name: name of the derived class (the parameter required for the base class, the parameter required for this class): Base Class Name (parameter table) {initialization of this class member}

The following is an example of zookeeper:

Once multiple classes are involved, the call sequence of each class must be described. In the case of inheritance, the calling sequence of the constructor is as follows:

-Call the base class constructor. The Calling sequence is the declaration order when they are inherited (from left to right)-call the constructor of the member object, the Calling order is in the order they declare in the class-the constructor of the derived class

The following is an example of zookeeper:

The same as the constructor, the constructor cannot be inherited, and the derived classes are declared on their own. The declaration method is the same as that of the general class destructor. It is worth noting that the calling of the destructor of the base class does not need to be displayed here. The system automatically and implicitly calls the destructor. At the same time, the calling sequence of the Destructor is opposite to that of the constructor.
The following is an example of zookeeper:

5-3 override the parent class Method

Generally, the method defined by the parent class can only operate on the members of the parent class. After the subclass inherits, the method that calls the parent class can only operate on the members of the parent class, when the subclass also wants to perform corresponding operations, the method of calling the parent class cannot be completed. In this case, the subclass needs to override the method of the parent class.
During runtime, the compiler will call the parent class or subclass method based on our call conditions. The column is as follows:

6. What is polymorphism and virtual function 6-1?

In actual situations, we often need to implement a function, that is, for the same function, different results will be obtained when different objects are running, this greatly facilitates programming.
To achieve this function, Zookeeper requires an important mechanism of C ++, namely polymorphism. The so-called polymorphism means that when sending the same message to be accepted by different types of objects, it may lead to completely different behaviors.
The implementation of zookeeper polymorphism relies on a dynamic binding technique. What is binding? Binding is the process of linking the program itself, and determining the relationship between the operation calls in the program and the code that executes the operation.
Zookeeper has two types of binding: static binding and dynamic binding. Static binding is also called static Association editing. It appears in the compilation stage. dynamic binding is also called Dynamic Association editing,Is the execution process of the program. The function to be called is determined only when the program is running.

6-2 virtual functions

Keyword keyword is used to prove a function has polymorphism.VirtualKeyword to mark it. The function that uses this tag is our virtual function. Virtual functions are generally declared as follows:

Virtual Return Value Function Name (parameter list)

Implicit Functions has two points to describe for virtual functions:

1. virtual can only be used to describe the prototype in the class declaration and cannot be used for function implementation. the virtual functions declared in the base class are automatically converted to virtual functions regardless of whether the derived classes are declared or not.

The following is an example of zookeeper:

How is the   virtual function implemented? Generally, the implementation of virtual functions is throughVirtual function tableFor short, V-Table. Virtual function tables are mainlyVirtual function address table of a classWhen a sub-class is operated using the pointer of the parent class, the virtual function table is a map that specifies the function to be called.

It is worth noting that:
1. the compiler stores the pointer of the virtual function table at the beginning of the object instance. The address of the object can be used to obtain the virtual function table.
2.The virtual functions are placed in the table in the declared order, and the parent class virtual functions are placed before the subclass virtual functions.
Compiler compiler previously mentioned that only the virtual modifier of a function can be used for dynamic compilation. Otherwise, the compiler does not know whether to compile later. It can be said that the essence of virtual functions isOverwrite is not a reload Declaration

Based on the features of the virtual function, the following points must be noted:

1. Only class member functions can be described as virtual functions. Virtual functions are only applicable to Class objects of the inheritance relationship. static member functions cannot be used as virtual functions, because static member functions are not limited to an object. inline Function and constructor cannot make virtual function 4. destructor can make virtual functions, usually virtual functions.
6-3 pure virtual functions and abstract classes

Based on the virtual function, we also have a virtual function called pure virtual function, which is a member function that is not actually implemented by the Base class and is left to the derived class for implementation, it is equivalent to retaining a position for the subclass so that the derived class can be implemented.
Pure virtual functions are generally defined as follows:

Vitural type function name (parameter table) = 0

Zookeeper can find that the virtual function equals 0 to the pure virtual function. Classes that contain pure virtual functions are abstract classes.
The abstract class of zookeeper isDeclared for the purpose of abstraction and DesignTo organize the relevant data and behavior in an inheritance hierarchy to ensure the required behavior of the derived class. For a function that cannot be implemented temporarily, it can be declared as a pure virtual function and left to the derived class for implementation.
Abstract classes are required for abstract classes.

1. abstract classes can only be used as base classes. 2. Objects of abstract classes cannot be declared, even classes that implement some pure virtual functions.

We hereby declare that:
This article is an original article. You are welcome to discuss it with those who love it. Thank you !!! In addition, if it is reproduced, please declare the source. Thank you !!!

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.