Super detailed introduction to C++ classes and objects

Table of contents

1. Introduction of class

1.1 So what is the difference between struct and class in C++

2. Class definition

There are two ways to define a class:

3. Class access qualifiers and encapsulation

4. Encapsulation

5. Class scope

6. Class instantiation

7. Class object model

7.1 How to calculate the size of a class object

8. this pointer

8.1 Characteristics of this pointer

Several frequently asked questions about this pointer


1. Introduction of class

Only variables can be defined in the C language structure. In C++, not only variables but also functions can be defined in the structure. For example: For beginners in the data structure, the stack implemented in C language can only define variables in the structure; now it is implemented in C++, and you will find that functions can also be defined in struct, but C++ prefers to write it as class

1.1 So what is the difference between struct and class in C++

C++ needs to be compatible with C language, so struct in C++ can be used as a structure. In addition, struct in C++ can also be used to define classes. It is the same as class definition class, the difference is that the default access right of class defined by struct is public, and the default access right of class defined by class is private. Note: There are also differences between struct and class in inheritance and template parameter list positions

2. Class definition

class className
{
// 类体:由成员函数和成员变量组成
};  // 一定要注意后面的分号

class is the keyword to define the class, ClassName is the name of the class, and {} is the body of the class. Note that the semicolon after the end of the class definition cannot be omitted. The contents of the class body are called members of the class: variables in the class are called attributes or member variables of the class; functions in the class are called methods or member functions of the class.

There are two ways to define a class:

1. All declarations and definitions are placed in the class body

Note: If a member function is defined in a class, the compiler may treat it as an inline function .

2. The class declaration is placed in the .h file, and the member function definition is placed in the .cpp file. Note: the class name needs to be added before the member function name::

3. Class access qualifiers and encapsulation

3.1 The access qualifier C++ implements encapsulation: use classes to combine object attributes and methods to make the object more complete, and selectively provide its interface to external users through access rights.

public,protected和private

1. Publicly modified members can be directly accessed outside the class

2. Protected and private modified members cannot be directly accessed outside the class (here protected and private are similar)

3. The scope of access rights starts from the occurrence of the access qualifier until the next occurrence of the access qualifier

4. If there is no access qualifier behind, the scope will go to }, that is, the end of the class.

5. The default access right of class is private, and struct is public (because struct is compatible with C) Note: access qualifiers are only useful at compile time, when data is mapped to memory, there is no difference in access qualifiers

Note: access qualifiers are only useful at compile time, when the data is mapped to memory, there is no difference in access qualifiers

4. Encapsulation

 The three major characteristics of object-oriented: encapsulation, inheritance, and polymorphism. In the class and object stage, it is mainly to study the encapsulation characteristics of the class, so what is encapsulation? Encapsulation: organically combine the data and the method of manipulating the data, hide the properties and implementation details of the object, and only expose the interface to interact with the object. Encapsulation is essentially a management that makes it easier for users to use classes. For example: for such a complex device as a computer, the only thing provided to the user is the switch button, input through the keyboard, a monitor, and a USB jack, etc., allowing the user to interact with the computer and complete daily affairs. But in fact, the real work of the computer is some hardware components such as CPU, graphics card, and memory.

For computer users, they don’t need to care about internal core components, such as how the circuits on the motherboard are laid out, how the CPU is designed inside, etc. Users only need to know how to turn on the computer and how to interact with the computer through the keyboard and mouse. Therefore, when the computer manufacturer leaves the factory, it puts a shell on the outside to hide the internal implementation details, and only provides external switches, mouse and keyboard jacks, etc., so that users can interact with the computer. Encapsulation in the C++ language can organically combine data and methods of manipulating data through classes, hide internal implementation details of objects through access rights, and control which methods can be used directly outside the class.

5. Class scope

A class defines a new scope, and all members of the class are in the scope of the class. When defining members outside the class, you need to use the :: scope operator to indicate which class domain the member belongs to.

6. Class instantiation

The process of creating an object with a class type is called instantiation of the class

1. A class is a description of an object. It is a model-like thing, which defines which members a class has, and defines a class without allocating actual memory space to store it;

2. A class can instantiate multiple objects, and the instantiated objects occupy the actual physical space and store class member variables

7. Class object model

7.1 How to calculate the size of a class object

A class can have both member variables and member functions, so what does an object of a class contain? How to calculate the size of a class?

Storage method of class objects

Only member variables are saved, and member functions are stored in public code segments

The size of a class is actually the sum of "member variables" in the class. Of course, pay attention to memory alignment and the size of the empty class. The empty class is special. The compiler gives the empty class a byte to uniquely identify the object of this class .

 memory alignment rules

1. The first member is at the address at offset 0 from the structure.

2. Other member variables should be aligned to an address that is an integer multiple of a certain number (alignment number). Note: Alignment = the smaller value between the compiler's default alignment and the member size. The default alignment number in VS is 8

3. The total size of the structure is: an integer multiple of the maximum alignment number (the largest of all variable types and the smallest default alignment parameter).

4. If a structure is nested, the nested structure is aligned to an integer multiple of its own maximum alignment, and the overall size of the structure is the integer of all maximum alignments (including the alignment of the nested structure) times.

8. this pointer

The C++ compiler adds a hidden pointer parameter to each "non-static member function", so that the pointer points to the current object (the object that calls the function when the function is running), and all "member variable" operations in the function body, All are accessed through this pointer. It's just that all operations are transparent to the user, that is, the user does not need to pass it, and the compiler completes it automatically.

8.1 Characteristics of this pointer

1. The type of this pointer: class type * const, that is, in member functions, the this pointer cannot be assigned a value.

2. Can only be used inside a "member function"

3. The this pointer is essentially the formal parameter of the "member function". When the object calls the member function, the object address is passed as the actual parameter to the this formal parameter. So the this pointer is not stored in the object.

4. The this pointer is the first implicit pointer parameter of the "member function". Generally, it is automatically passed by the compiler through the ecx register and does not need to be passed by the user.

1. Where does this pointer exist?

In fact, the compiler adds relevant code to obtain the first address of the object when generating the program. And store the obtained first address in the register ECX (VC++, VS compiler is placed in ECX, other compilers may be different). That is, other parameters of member functions are normally stored on the stack. The this pointer parameter is stored in a register. Because the static member function of the class does not have the parameter of this pointer, the static member function of the class cannot call the non-static member variable of the class

2. Can this pointer be empty?

It can be empty, but the member variable cannot be accessed through the pointer (that is, the null pointer is dereferenced)

#include<iostream>

class List {
public:
	void Init()
	{
		_size = 0;
		_arr = new int[10];
		_front =_arr;
		_tail = _arr;
	}
	void my_printf()
	{
		std::cout << this << std::endl;
		std::cout <<"my_printf" << std::endl;
	}
private:
	int _size;
	int* _front;
	int* _tail;
	int* _arr;
};

int main()
{
	//编译报错,运行崩溃,正常运行
	List *L1=nullptr;
	//L1->Init();// 运行崩溃
	L1->my_printf();//正常运行
}

 

	(*L1).my_printf();//正常运行

 Whether there is dereferencing depends on whether the thing on the right is dereferencing the this pointer in it, rather than looking at the symbol

Several frequently asked questions about this pointer

1. When is the this pointer created
? This is constructed before the execution of the member function, and cleared after the execution of the member ends.
But if there is no method in the class or struct, they have no constructor and can only be used as a C struct. If defined in the way of TYPE xx, memory is allocated in the stack, and the value of this pointer is the address of this memory at this time. If the new method is used to create an object, the memory is allocated in the heap, and the new operator returns the allocated address through eax (accumulation register), and then sets it to the pointer variable. Then call the constructor (if there is a constructor), then pass the address of this memory block to ecx, and then see the answer above for how to deal with it in the constructor

2. Where is the this pointer stored
The this pointer will have different placements depending on the compiler. It may be a stack, it may be a register, or even a global variable. At the assembly level, a value can only appear in three forms: immediate value, register value, and memory variable value. Either stored in registers or stored in memory, they do not correspond to high-level language variables.

3. How does the this pointer pass the function in the class? binding? Or is the first parameter of the function parameter the this pointer? So, how does the this pointer find the "function after the class instance"?
Most compilers pass this pointer through the ecx (count register) register. In fact, this is also an unspoken rule. Generally speaking, different compilers will follow consistent parameter passing rules, otherwise obj generated by different compilers will not be able to match.
Before the call, the compiler will put the corresponding object address into eax. this is passed as the first parameter of the function parameter. The this pointer is generated before the call. As for the "function after the class instance", there is no such statement. When the class is instantiated, only the variable space in the class is allocated, and no space is allocated for the function. Since the class's function definition is complete, it's there and won't run

4. How does the this pointer access the variables in the class
If it is not a class but a structure, then how to access the variables in the structure through the structure pointer? If you understand this, it is easy to understand the problem.
In C++, there is only one difference between a class and a structure: the members of a class are private by default, while the structure is public.
this is the pointer of the class, if it is replaced with a structure, then this is the pointer of the structure.

5. Only after we obtain an object can we use the this pointer through the object. If we know the location of the this pointer of an object, can we use it directly?
The this pointer is only defined in member functions. Therefore, after you get an object, you cannot use the this pointer through the object. Therefore, we cannot know the location of the this pointer of an object (the location of the this pointer is only available in member functions). Of course, in member functions, you can know the location of this pointer (you can get it through &this), or you can use it directly.

6. After each class is compiled, is a function table in the class created to save the function pointer so that it can be used to call the function?
Ordinary class functions (whether they are member functions or static functions) do not create a function table to save function pointers. Only virtual functions are placed in the function table. However, even if it is a virtual function, if the compile-time can clearly know which function is called, the compiler will not call the function indirectly through the pointer in the function table, but will call the function directly. It is precisely because of the existence of this pointer that it is used to point to different objects, so as to ensure that calling the same function between different objects can not interfere with each other.
 

Guess you like

Origin blog.csdn.net/m0_74234485/article/details/129866713