C + + Const member functions

Source: Internet
Author: User

Pre-knowledge1. Code Conversion Analysis Skillsin the early days some compilers translated C + + code into C code and then used the C compiler to build the executable file. One translation is to explicitly add the this pointer to the first parameter position of the member function, because C does not have the support of OOP and automatically passes the address of the object to the parameter this when the member function is called.
This process is explained in the following code:
#include <iostream>#include<cstdio>using namespacestd;classdog{ Public: Dog (unsigned en=0): Energe (en) {}voidBark ()Const        {         for(size_t i =0; i < Energe; i++) cout<<"Wang wang!\n"; }    voidFeed (unsigned add) {Energe+=add; }Private: unsigned energe;};intMain () {dog Dog; Dog.feed (2);        Dog.bark (); return 0;}

Translation conversion

// prototype Conversion void Feed (const dog*this); void Feed (dog*This, unsigned add); // the conversion of the call Dog.feed (2);   ----->  2); Dog.bark ();     ----->  Bark (&dog);
Now the C + + compiler may not work this way, but if you use this transformation to apply to actual programming code analysis, many of the code and syntax features will be solved.

2, the top-level const, the underlying const

top layer Const: The pointer variable itself is a constant. (The top-level const is not suitable for referencing because a reference is inherently a constant, always referencing an object until it dies)

such as int* const P = &a;

underlying const: the object that the variable points to (or refers to) is treated as a constant. (Note the term here: is considered, because the object is not necessarily a constant, it may be the underlying const pointer, the reference of wishful thinking)

such as the const int*p;    int const *P; The two are equivalent

Const int& R;

A non-underlying const pointer that has read and write rights to the object it points to, so that to ensure data security, it can only point to a very low-volume object.

int a=1; Const int 2 ; int*p1 = &a;  // OK P1   = &b;      // Error not allowed

A low-level const pointer that has only read rights to the object it points to. Therefore, it can point to constants and to a very good amount.

int a=1; Const int 2 ; Const int*p1 = &a;  // OK  = &b;           // OK

3, whether the parameter of the function is the underlying const can be used as the basis for overloading

As an example, the following 2 functions can be overloaded.

void foo (constint*p);     Avoid foo (int*p);           B

When the compiler resolves the overload, it determines which version to call based on the parameters passed.

When only version A is present, a pointer to a very literal int, or a pointer to a constant int, can be invoked successfully.

When only version B is present, a pointer to a very literal int can be called successfully, but a pointer to a constant int is not allowed.

When both A and B are present, when overloaded, if a pointer to a very heavy int is passed, then version B is preferred, because this is the best match.

If you are passing a pointer to a constant int, use version A.

In addition, whether the parameter itself is const is not the basis for overloading, and the following cannot be overloaded.

void foo (constint  a); void foo (int  a); // in C, the parameter decoration is const and does not use the const modifier to be treated like a compiler, C + + is compatible with C, and this policy is also used. So the two are equivalent. 

If a member function does not logically modify the State (field) of an object, it should be defined as a const function

In the dog code above, if you remove the const modifier from the bark function and try to invoke the bark function with a const object, you will find the compiler error.

void bark () {     for0; i < energe; i++)         "Wang wang!\n" ;} ////// /////////////////// Const  // error prompt for type incompatibility

In terms of business logic, the bark function simply outputs the message on the screen, without changing the state of the object, even if it is a const object that must be successfully invoked.

The error here is clearly the problem with the bark function: it should be defined as a const function, which is clear to all. But why is this so?

The code for the error is equivalent to the following C code, as described at the beginning of the analysis method.

Const Dog Dog;bark (&dog)      //Bark after conversion prototype: void Bark (dog*this);

Obviously, assigning a constant pointer to a non-const pointer is not allowed.

For example, the string class in the C + + standard library, whose member functions are const-decorated for getting the length of a string. If that's not the case, then the string constants can't get their lengths, which is ridiculous!

Const;        const;  


Const member functions can form overloads

Does the member function have both a const version and a non-const version? Can be overloaded? Yes.

Similarly, the first introduction to the 1th analysis method, the conversion to C code. And then, according to the analysis of article 3rd, we can. Don't repeat it here.

The most common is that, by convention, when the index operator [] is overloaded, both a const version and a non-const version are written.

For example, the [] operator function of std::vector

Reference       operator[] (Size_type POS);         operator Const;

Summarize

1. If a member function does not logically modify the State (field) of an object, it should be defined as a const function

2.

If the object is const, it can only call the const member function.

If the object is a normal non-const object:

A member function called is a non-const function, and it is rightfully called.

A member function called is a const function, and of course it can be called. (The underlying const pointer can point to a very mass object)

A member function that is called has both a const version and a non-const version, and the non-const member function is called first, and the compiler always uses the most matching version.

C + + Const member functions

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.