The this pointer in C + + and the Common object _c language

Source: Internet
Author: User

C + + this pointer detailed
This is a keyword in C + + and a constant pointer to the current object (specifically the first address of the current object). With this, you can access the member variables and member functions of the current object.
The current object, which is the object being used, for example, for Stu.say (), Stu is the current object, and the system is accessing the STU member function say ().
Suppose this points to the Stu object, and in the following statement, this is the same as the value of Pstu:

Student Stu; Creating objects through the Student class
Student *pstu = &stu;

[Example] to access a member variable through this:

Class student{
private:
  char *name;
  int age;
  float score;
Public:
  void SetName (char *);
  void setage (int);
  void SetScore (float);
void Student::setname (char *name) {
  this->name = name;
}
void student::setage (int age) {
  this->age = age;
}
void Student::setscore (float score) {
  this->score = score;
}

In this case, the name of the function argument and the member variable is not problematic because the member variable is accessed through this, and the variable without this is a local variable within the function. For example, for the This->name = name statement, the assignment number is to the left of the class's member variable, and to the right is the SetName function's local variable, which is the parameter.

The following is a complete example:

#include <iostream>
using namespace std;
Class student{
private:
  char *name;
  int age;
  float score;
Public:
  void SetName (char *);
  void setage (int);
  void SetScore (float);
  void say ();
void Student::setname (char *name) {
  this->name = name;
}
void student::setage (int age) {
  this->age = age;
}
void Student::setscore (float score) {
  this->score = score;
}
The Age of Void Student::say () {
  cout<<this->name<< is "<<this->age<<" and the result is "<< this->score<<endl;
}
int main () {
  Student stu1;
  Stu1.setname ("Xiaoming");
  Stu1.setage ();
  Stu1.setscore (90.5f);
  Stu1.say ();
  
  Student STU2;
  Stu2.setname ("Li Lei");
  Stu2.setage ();
  Stu2.setscore ();
  Stu2.say ();
  return 0;
}

Run Result:

Xiaoming's age is 15, the result is 90.5
Li Lei's age is 16, the result is 80

objects are similar to ordinary variables; Each object takes up several bytes of memory to hold the value of the member variable, and the memory used by the different objects does not overlap, so action object A does not affect object B.

In the example above, when you create an object STU1, the this pointer points to the first byte of the memory where STU1 resides, and its value and &STU1 are the same; When you create the object stu2, this equals &stu2; creates the object stu3.

We might as well prove it by adding a member function to the Student class, outputting the value of this, as follows:

void Student::p rintthis () {
  cout<<this<<endl;
}


Then create the object in the main function and invoke Printthis:

Student stu1, *pstu1 = &stu1;
Stu1.printthis ();
cout<<pstu1<<endl;
Student stu2, *pstu2 = &stu2;
Stu2.printthis ();
cout<<pstu2<<endl;

Run Result:

0X28FF30
0x28ff30
0x28ff10
0x28ff10

As you can see, this does point to the first address of the current object, and for different objects, this is not the same value.

A few notes:
This is a constant pointer, and its value cannot be modified, and all attempts to modify the pointer's operations, such as assignment, increment, decrement, are not allowed.
This can only be used within a member function and is not meaningful or illegal elsewhere.
This only makes sense when an object is created, and therefore cannot be used in a static member function, as the following will refer to.
What the hell is this?

In fact, this pointer is implicitly passed as a parameter of a function, it does not appear in the argument list, when the member function is invoked, the system automatically gets the address of the current object, assigns it to this, completes the pass of the parameter without user intervention.

This is an implicit argument, which is essentially a local variable of a member function that does not occupy the object's memory and is assigned only when a member function call is made, and this is destroyed after the function call has ended.

Because this is a parameter that represents the first address of an object, it can only be used inside a function, and the object is instantiated after it makes sense.

C + + constant objects and their members
Although C + + has taken many effective measures (such as setting private protection) to increase the security of data, but some data is often shared, people can access the same data object in different situations. Sometimes inadvertent misoperation can change the state of the data, which is not what people want to happen.

To make the data shared within a certain range, and to ensure that it is not arbitrarily modified, you can use const, that is, to define the relevant data as constants.
Regular objects

Specifies that the object is a regular object when the object is defined. A regular object must have an initial value, such as:

  Time Const T1 (12,34,46); T1 is a constant object


Thus, in all cases, the value of all members in the object T1 cannot be modified. Objects that want to ensure that data members are not changed can be declared as constant objects.

The general form of defining a constant object is:

  Class name Const object name [(argument list column)];


You can also write the const on the left:

  Const class Name Object name [(Argument table column)];

They are equivalent.

If an object is declared as a regular object, you cannot call the non-const member function of the object (except for implicit constructors and destructors that are automatically invoked by the system). For example, for the time class that is already defined in example 9.7, if there are

  Const Time T1 (10,15,36); Defines a constant object T1
  t1.get_time ();//attempt to invoke a non-const member function in a constant object T1, illegal


This is to prevent these functions from modifying the values of the data members in the regular object.

Can not rely on the programmer's careful to ensure that the program does not make mistakes, the compilation system fully consider the possible situation, the security of the factors to intercept. Now, the compilation system checks only the declaration of the function, and if it finds that the member function of the regular object is invoked, and the function is not declared as const, the error is brought to the attention of the programmer.

It is easy to refer to a data member in a constant object by simply declaring the member function as Const. Such as:

  void Get_time () const; Declare a function as const


This means that get_time is a const function, that is, a constant member function.

A regular member function can access data members in a constant object, but still does not allow you to modify the values of the data members in the constant object. Sometimes in programming, it is necessary to modify the value of a data member in a constant object, ANSI C + + takes into account the actual programming needs, this special processing, the data member declared as mutable, such as:

  mutable int count;


Declare count as a mutable data member, so that you can modify its value with a member function declared as Const.
Regular Object Members

You can declare the members of an object as const, including constant data members and constant member functions.

1) Regular data member
Its function and usage are similar to those of general variables, with the keyword const to declare the constant data member. The value of a constant data member cannot be changed.

One thing to note: You can initialize a regular data member only through the constructor's parameter initialization table. For example, a constant data member hour is defined in the class body:

  const int hour; Declaring hour as a constant data member

You cannot use a method that assigns an initial value to a regular data member in a constructor, and the following practices are illegal:

  Time::time (int h) {
    hour=h;
  }//illegal


Because a regular data member cannot be assigned a value.

Defining a constructor outside of a class should be written in the following form:

  Time::time (int h): Hour (h) {}///hour initialization of a constant data member via a parameter initialization table


The data members of a constant object are constant data members, so the constructor of the regular object can initialize the regular data member only with the parameter initialization table.


2) constant member function
As mentioned earlier, general member functions can refer to non-const data members in this class, or modify them. If you declare a member function as a regular member function, you can reference only the data members in this class, and not modify them, such as for output data only. Such as

  void Get_time () const; Note that the const position is after the function name and parentheses


A const is a part of a function type that has a const keyword when declaring a function and defining a function, without adding a const to the call. A regular member function can reference a const data member or a data member that is not a const. A const data member can be referenced by a const member function, or by a member function that is not a const. The specific situation can be expressed in the following table.

So how do you make use of the regular member function?
If you are in a class, some data members are allowed to change their values, and other data members are not allowed to change their values, you can declare some data members as const to ensure their values are not changed, you can refer to the values of those data members with non-const member functions, and modify the values of non-const data members.
If you require that all data members ' values are not allowed to change, you can declare all data members as const, or declare objects as const (constant objects), and then use the const member function to refer to data members, so that the role of "double insurance" is to effectively guarantee
If you have defined a constant object, you can call only the const member function in it, not the non-const member function, whether or not the function modifies the data in the object. This is to ensure the security of the data. If you need to access data members in an object, you can declare all member functions in a regular object as const member functions, but make sure that the data members in the object are not modified in the function.

Don't mistake a member function in a constant object as a constant member function. A constant object only guarantees that its data member is a constant data member whose value is not modified. If a member function in a constant object is not declared with a const declaration, the compilation system handles it as a non-const member function.

It is also important to note that a regular member function cannot invoke another non-const member function.

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.