C++ Classes and Objects (1) Introduction of Classes

Table of contents

1. The concept of class

Second, the introduction of the class

3. Class definition 

1. Define a class

2. The difference between struct and class

3. The declaration and implementation separation of member functions in the class

4. Encapsulation and class access qualifiers

1. Encapsulation

2. Class access qualifiers       

5. Class scope and life cycle

6. Instantiation of the class

【concept】

1. Implicit creation

2. Explicit creation

3. Explicit new creation

7. Storage methods of classes and objects

1. Member function storage method conjecture

2. The distribution of members in the class in memory  

3. The storage location of the class in memory

4. The storage location of the object in memory

3.1 Global objects

3.2 Local objects

3.3 Static local objects

3.4 Dynamic Objects

[code demo] 

 【Memory layout】

Eight, calculate the size of the class


1. The concept of class

1. What is it?

        It is an abstraction of things that have the same properties and behaviors.


2. Why?

        Put related data and functions together for easy management, and classes are the premise of object-oriented programming.


3. How to use it?

        Put the attributes and behaviors (implemented by functions) of the things to be described together to form a class.


Second, the introduction of the class

1. Struct is upgraded to a class        

        In C++, struct is not only compatible with the syntax of structures in C language, but also struct is upgraded to a class in C++.


2. Functions can be defined in the class
        The class contains two parts member variables and member functions. So in C++, not only variables can be defined in the structure, but also functions can be defined.


3.class can also define classes

        In addition to struct, class can also be used to define classes in C++, and class is more commonly used to define classes in C++ .

Extension: The subtle difference between struct in C and C++

1. In C, use typedef to rename the structure, and it will take effect after the last line. The structure name used in the structure must also be accompanied by struct.


2. In C++, the class name can be used directly in the class without even using typedef renaming.


3. Class definition 

1. Define a class

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

struct structName //法二
{
 // 类体:由成员函数和成员变量组成
 
}; // 一定要注意后面的分号
        class (or struct) is the keyword to define the class, className (structName) 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 .

2. The difference between struct and class

In C++, either struct or class can be used to define a class. The difference between the two is that
        if no qualifier is added, struct is public by default, and class is private by default.

extension: class access qualifier       

3. The declaration and implementation separation of member functions in the class

a. The declaration and implementation of member functions are all placed in the class body. Note: If the member function is defined in the class , the compiler may treat it as an inline function .

b. The declaration of the member function is placed in the .h file, and the implementation of the member function is placed in the .cpp file.
(Note: When the declaration and implementation are separated, because the declaration is in the class domain, the class name and domain scope qualifier (::) need to be added before the name of the member function during definition to find the class. )

        

In large-scale projects, it is recommended to separate the declaration and implementation of the member functions in the class like ordinary functions. The significance of separating the declaration and definition of the member functions in the class is to facilitate reading the code .

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

        After the declaration and implementation are separated, the member functions of the class will no longer be regarded as inline functions. (The declaration and implementation of the inline function cannot be separated, the inline function will not enter the symbol table, and the address of the implementation cannot be found by the declaration when linking)


Extension 2. When the declaration and definition are separated: if we do not add the domain name of the class when defining, then two functions with the same name will appear in the class domain and the global domain, which is feasible and does not constitute function overloading. ( functions in different domains do not constitute overloading )   


4. Encapsulation and class access qualifiers

1. Encapsulation

1. What is it?

        It is essentially the management of data: the implementation details of the object's attributes and methods are hidden, only the interface is exposed to the outside world, and the access level for reading and modifying attributes in the program is controlled.


2. Why?

        Improve program security and maintainability ( ease of improvement ).


3. How to do it?

         The way of C++ to achieve encapsulation: use a class to combine attributes and methods, and selectively provide its interface to external users by setting access permissions. 

2. Class access qualifiers       

public (public), private (private), protected (protected)


5. Class scope and life cycle

1. The scope of the class

         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 . 


2. Class life cycle

        The life cycle of a class is related to the storage location. For example, global classes and static classes are stored in the static area, and its life cycle is the entire project. The life cycle of a class in a function follows this function...


6. Instantiation of the class

【concept】

The process of creating an object with a class is called instantiation of the class. A class can instantiate multiple objects.


        The class does not take up space, and it will take up space after being instantiated into an object, which is used to store class member variables . But we can also calculate the size of the space occupied by the object through the class.

        In the same way, defining a structure does not take up space, only defining a structure variable will take up space, but we can also use the sizeof structure name to calculate the space occupied by a structure variable. 

1. Implicit creation

Created on the stack by calling the default constructor by the compiler.

class A{};
A a;

2. Explicit creation

Actively call the constructor in the code and create it on the stack.

class A{};
A a = A();

3. Explicit new creation

The new keyword is used to allocate memory creation in the heap.

class A{};
A* pa = new A();

The new object must be received by a pointer, and the object needs to be explicitly deleted to release the memory.


7. Storage methods of classes and objects

1. Member function storage method conjecture

Member function storage method conjecture 1: store both the address of the member function and the member variable

There is a problem: the member functions to be called are all the same, so there is no need to store the address of a member function for each object


Member function storage method conjecture 2: store the address of the member function in a table separately, and then store the address of an additional table when storing

There's nothing wrong with this approach, but it's not used here.


Conjecture 3 on member function storage method: only member variables are stored, and member functions are uniformly stored in the public code area.

This scheme is the storage scheme of member functions . The address of the function will not be found in the object at runtime, and the address of the function will be found in the public code area according to the function name when compiling and linking.

So when the class encounters the following situations, the program will not crash. (Because the address of the member function is not found in the class, it is found in the public code area, so the class is instantiated as nullptr and we can still call the member function)

 

2. The distribution of members in the class in memory  

1) Ordinary member variables in the class ------------ stack
2) Static member variables in the class ------------ static area
3) Reference variables in the class ------------ Look at the referenced variable
4) const variable in the class ------------ stack (const modification only limits the variable to read-only, the essence is still Variable, the storage location depends on the variable itself, so the local variable modified by const is still on the stack and can be modified through the pointer.)

5) Class member functions ------------ Ordinary member functions and static member functions are all in the code area

3. The storage location of the class in memory

        The class will not be stored in memory, the class is just a template to tell the program how to create an object, how many bytes are needed, and how to destroy it.

        Objects instantiated from a class are stored in memory.

4. The storage location of the object in memory

3.1 Global objects

        The global object is stored in the global (static) storage area , and is released by the system call destructor after the program ends.


3.2 Local objects

        Local objects are stored on the stack . Its life ends when the scope ends, and its destructor is automatically called, that is, the object is automatically cleaned up.


3.3 Static local objects

        Static local objects are stored in the global (static) storage area , and their life still exists after the scope ends, that is, the destructor of the object will not be called at this time until the end of the entire program.


3.4 Dynamic Objects

        Dynamic objects (that is, new objects) are stored in the heap , and their life ends when they are deleted. The pointers used to create dynamic objects are stored on the stack.
        Note: For new objects, you must use delete to explicitly call the destructor, otherwise the program will not call its destructor, resulting in memory leaks.


[code demo] 
class A{
};
class B{
};
class C{
};
class D{
};

A a;  //全局对象
int main(){
	B b;  //局部对象
	static C c;  //静态局部对象
	D *d = new D;  //动态对象
	delete d;
	return 0;
}

 【Memory layout】


Eight, calculate the size of the class

1. Calculate the size of the member variable

        Like the structure, the class also obeys the memory alignment rules. Starting from the second member variable, the starting position needs to be calculated. Choose the smaller one between its own size and the default alignment number (the default alignment number in the VS compiler is 8). the one. Finally, the entire class must also be aligned: the size of the class must be an integer multiple of the default alignment.

        When sizeof calculates the size of the class, it ignores the size of static member variables.

2. Calculate the size of the member function

        When calculating the size of a class, member functions are not considered, so there is no need to add the size of the function pointer.

3. Calculate the size of the empty class

        Note that the size of a class without member variables (including empty classes) is 1 byte and does not store data. The purpose is to occupy space, identify the existence of objects, and distinguish different objects.


Summarize:

Calculating the size of a class is to calculate the size of all (non-static) member variables          in the class in a memory-aligned manner .

Guess you like

Origin blog.csdn.net/look_outs/article/details/129029360