C++ Programming

Member Function in C++ with Examples

member functions

The nature of member functions

The member function of the class (referred to as the class function) is a kind of function, and its usage and function are basically the same as the general function. Similarly, it also has return values ​​and function types. The difference between it and general functions is only: it is a member of a class, now in the class body. It can be designated as private, public or protected. When using a class function, pay attention to the permission to call it (whether it can be called) and its scope (the function can be used What range of data and functions to use). For example, private member functions can only be called by other member functions in this class, but cannot be called outside the class. Member functions can access any member of this class (including private and public), but to refer to data valid in this scope.

The general approach is to specify the member functions that need to be called by the outside world as public, which are the external interface of the class. In fact, not all member functions are designated as public. Some functions are not intended to be called for the outside world, and if the member functions in this class are called, they should be designated as private. The role of this function is to support the operations of other functions are utility functions of other members of the class, and users cannot call these private tool function. The member function of a class is a very important part of the class body. If a class does not contain member functions, then Equivalent to the structure in C language does not reflect the role of classes in object-oriented programming.


allpcb circuit

Amazon Purchase Links:

Top Gaming Computers

Best Laptops

Best Graphic Cards

Portable Hard Drives

Best Keyboards

Best High Quality PC Mic

Computer Accessories

*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!

 Define member functions outside the class

The member functions you saw earlier are defined in the class body. You can also declare only member functions in the class body, The function definition is performed outside the class. Such as

 

Note: When directly defining a function in the class body, you do not need to add the class name in front of the function name, because which one the function belongs to This category is self-evident. But when the member function is defined outside the class, the class name must be added to the function name to be qualified (qualified), “:” is a field qualifier or scope operator. Use it to declare that a function is a In which category. Student::display() represents the display function in the scope of the Student class, which is The display function in the Student class. If there is no limitation of “Student:;”, display() defaults to the current effective operation The display function in the domain, for the above program segment, refers to the display function in the global scope, not The display function in the Student class. And different classes may have functions with the same name (but the functions may be different), used as Using domain qualifiers to qualify, it clearly indicates the function in which scope, that is, which class of function. If there is no class name before the scope operator “:”, or there is neither class name nor scope before the function name Operator “:”, such as

:: display ()

or

display ()

It means that the display function does not belong to any class. This function is not a member function, but a global function, that is, general function. The class function must be declared in the class body first, and then defined outside the class, that is to say, the position of the class body should be in the function Before the definition (as shown above), Otherwise, errors will occur during compilation. Although the function is defined outside the class, it will be found according to the function prototype declared in the class when the member function is called The definition of the function (function code) to execute the function. Description: Declare member functions inside the class, and define member functions outside the class. This is a part of program design.

A good habit. If a function has only 2 to 3 lines in its function body, it can generally be defined in the class body when the class is declared. Functions with more than 3 lines are generally declared inside the class body and defined outside the class. This not only reduces the length of the class body, but also makes The class body is clear, easy to read, and can separate the interface of the class from the implementation details of the class. Because from the definition of the class user only see the prototype of the function, but not the details of the function execution. From the perspective of the user of the class, the class function is more like a black box hides the details of execution. In doing so, the quality of software engineering is improved.



Built-in member function (inline member function)

Class member functions can also be designated as built-in functions. The size of the member functions defined in the class body is generally very small, and the time taken by the system to call the function the cost is relatively large. The time cost of calling a function is much greater than that of a small-scale function body Execution of all sentences Line time. In order to reduce time overhead, if the member functions defined in the class body do not include control structures such as loops, The C++ system will automatically treat them as inline functions. In other words, call these into the program When calling a member function, it does not actually execute the function call process (such as retaining the return address, etc.), but replaces the function with Code is embedded in the calling point of the program. This can greatly reduce the time overhead of calling member functions. C++ requires the keyword inline declaration for general built-in functions, but for member functions defined in the class, you can omit inline, because these member functions have been implicitly designated as built-in functions. Such as

 

Explicitly declare the display function as a built-in function. The above two writing methods are equivalent. For functions defined in the class body Count, generally write inline. People should pay attention to: If the member function is not defined in the class body, but defined outside the class, the system does not default it For built-in functions, the process of calling these member functions is the same as that of calling general functions. If you want to Member functions are designated as built-in functions and should be explicitly declared in inline. Such as

 

For those that need to be processed as built-in functions, just make an inline declaration in the function definition or the function prototype declaration. (One of the two is fine). It is worth noting that if the inline function is defined outside the class, the declaration of the class The definition of the member function and the member function are placed in the same header file (or written in the same source file), otherwise it cannot be compiled Perform replacement (embed a copy of the function code into the function call point). But doing so is not conducive to the interface and the class To achieve separation is not conducive to information concealment. Although the execution efficiency of the program has been improved, from the perspective of software engineering quality Look, this is not a good way. Only when the scale of the member function defined outside the class is small and the calling frequency is high, it is designated as a built-in function.


Storage of member functions

When defining objects with classes, the system allocates storage space for each object. If a class includes data and functions Number, logically speaking, to allocate storage space for data and function code (referring to compiled object code) respectively. If you use The same class defines 10 objects, so do you need to allocate storage for each object’s data and function code separately? Unit and “package” them together (as shown in below Figure )?

Member Function

In fact, this is not the case. After analysis, it can be seen that the values ​​of data members in different objects of the same type are generally different The same, but the code of the function of different objects is the same, no matter which object’s function code is called, it is actually adjusted The same code is used. In this case, open up 10 segments of space in the memory to store 10 identical internal The function code segment of content is obviously unnecessary. People naturally think: Can you just use a space to store this common The target code of the function, when calling the function of each object, all call this common function code, as shown in below Figure.

Member Function

Obviously, this will greatly save storage space. The C++ compilation system does exactly this, so every object The storage space occupied is only the storage space occupied by the data members of the object, and does not include the storage space occupied by the function code storage. If one of the following classes is declared:


Readers can use the following statement to get the number of bytes occupied by this type of object: cout << sizeof (Time) << endl;

In the Visual C++ environment, the output value is 12. This proves that the space occupied by an object only depends on It is the space occupied by the data member in the object, and has nothing to do with the member function. The target code of the function is stored in the object empty Outside of time. If 10 objects are defined for the same class, the member functions of these objects correspond to the same function Code segment instead of 10 different function code segments. It should be noted that although the same function code is executed when calling member functions of different objects, the execution The row results are generally not the same. For example, when the member function display of the stud1 object is called, the output is the object

The stud1 data num, name and sex values, when calling the member function display of the stud2 object, the output is The data num, name and sex of the object stud2 have different results. Because the member function of the object stud1 visits The question is about the members of this object. Then, a problem occurred: different objects use the same function code segment, how can it be separated How to operate on the data in different objects? Originally, C++ specifically set up a pointer named this for this purpose. Point to different objects, when the member function of the object stud1 is called, the his pointer points to stud), the member function access

Is the member of stud1. When the member function of the object stud2 is called, the this pointer points to stud2, and the member The function visits the members of stud2. Need to explain: Month

(1) Regardless of whether the member function is defined in the class or outside the class, the storage method of the code segment of the member function is the same Similarly, it does not occupy the storage space of the object. Don’t mistake the code segment of the member function defined in the class to occupy the object The storage space of the member function defined outside the class does not occupy the storage space of the object.

(2) Don’t confuse this storage method of member functions with the concept of inline (built-in) functions. Don’t mistake A member function declared inline (or inline by default), its code segment occupies the storage space of the object, instead of inline

The code segment of the declared member function does not occupy the storage space of the object. Regardless of whether it is declared inline or not, the code segment of the member function does not occupy the storage space of the object (readers can go to the computer Verify). The function of the inline declaration is to copy and insert the code segment of the function into the function call when the function is called. Use a point, and if you don’t use the inline statement, when the function is called, the process transfers to the entry address of the function code segment. After the function code segment, the process returns to the function call point. The inline function only affects the execution efficiency of the program. Whether the number occupies the storage space of the object is irrelevant, they do not belong to the same category and should not be confused.



 (3) Someone may ask: Since the code of the member function is not placed in the storage space of the object, then I said earlier Is the statement of “the member function display of the object stud1” wrong? It should be explained:

“Member function” is from a logical point of view, and the storage method of member functions (not stored in the space of the object), From a physical point of view, it is optimized by the computer according to The two principles are not contradictory. Physical realization must ensure the logical realization. For example, someone who has a lot of money can put it at home or rent it in the bank in his safe, although the safe is not physically in his home, he rented the safe. This money is undoubtedly for him, this is from a logical point of view. Similarly, although member functions are not placed in the storage space of the object, But from a logical point of view, member functions are encapsulated in an object together with data, and only functions of members in this object are allowed. Access to private data in the same object. Therefore, “call the member function display of the object stud1, and output the object The hour and minute data in stud1 will not cause misunderstanding. As a programmer, it is beneficial to understand some knowledge of physical implementation, which can deepen the problem understanding.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button