Examples of class and object encapsulation and function in C ++, and examples of encapsulation
1. Concepts and encapsulation of Classes
1. What is encapsulation?
The first layer: encapsulation is the most basic feature of object-oriented programming. Data (attributes) and functions (methods) are combined into a whole, which is implemented by classes and objects in the computer world. (Encapsulate attributes and methods)
Second-level meaning: encapsulate objective things into abstract classes, and classes can only allow trusted class or object operations for their own attributes and methods to hide untrusted information. (Access Control for attributes and methods)
2. Class Access Control
In C ++, you can define the access level for class attributes and methods. The attributes and Methods Modified by public can be accessed inside the class or outside the class. Private-modified attributes and methods can only be accessed within the class.
3. Significance of Classes
Classes encapsulate attributes and methods and control access to class attributes and methods.
Class is a type of things that we abstract based on objective things. Then we define objects with classes to form specific individuals of such things.
A class is a data type. A class is abstract, and an object is a specific variable that occupies memory space.
4. Circle class abstraction and Encapsulation
# Include
Using namespace std;
/* Abstract a Circle class and encapsulate the attributes and methods of the Circle */class Circle
{
Private:
Double r;/* radius attribute of the circle class */
Public:
Void setR (double r)/* set the circle radius */
{
This-> r = r;
}
Double getR ()/* Get the circle radius */
{
Return this-> r;
}
};
2. Constructor
1. Preface
When creating an object, we often need to perform initialization operations, such as assigning initial values to attributes. To solve this problem, the C ++ compiler provides constructors to process object initialization. A constructor is a special member function. Unlike other member functions, a constructor is automatically executed when an object is created without calling it.
2. constructor definition and calling Method
Definition: a c ++ class can define special member functions with the same class name. Such member functions with the same class name are called constructors. A constructor can have a list of parameters, but cannot return values.
Call: Generally, the C ++ compiler automatically calls constructor, but in some cases, you need to manually call constructor.
3. constructor Classification
No parameter constructor: the constructor does not have any function parameters.
Constructor with parameters: constructor has function parameters.
Copy constructor: const ClassName & vriable.
4. Example and call of a constructor without Parameters
# Include
Using namespace std;
/* Abstract a Circle class and encapsulate the attributes and methods of the Circle */class Circle
{
Private:
Double r;/* radius attribute of the circle class */
Public:
Circle ()/* No parameter constructor */
{
Cout <"No parameter constructor executed" <endl;
}
Void setR (double r)/* set the circle radius */
{
This-> r = r;
}
Double getR ()/* Get the circle radius */
{
Return this-> r;
}
};
Int main ()
{
/* Method of calling a constructor without parameters */
Circle circle1, circle2;
}
5. Example and call of constructor with Parameters
# Include
Using namespace std;
/* Abstract a Circle class and encapsulate the attributes and methods of the Circle */class Circle
{
Private:
Double r;/* radius attribute of the circle class */
Public:
Circle (int a, int B)/* constructor with parameters */
{
Cout <"the constructor with parameters is called" <endl;
}
Void setR (double r)/* set the circle radius */
{
This-> r = r;
}
Double getR ()/* Get the circle radius */
{
Return this-> r;
}
};
Int main ()
{
/* Method 1 for calling a constructor with parameters */
Circle circle1 (1, 2 );
/* Method 2 of calling a constructor with parameters: the programmer calls the constructor manually */
Circle circle2 = Circle (1, 2 );
}
6. copy constructor example and call
1. Call Method for copying Constructors
When object 1 is used to initialize object 2, the copy constructor is called.
The copy function is called when object 2 is initialized in brackets of object 1.
When an object (here it is an element rather than a pointer or reference) is used as a function parameter, the process of passing the real parameter to the form parameter will call the copy constructor.
When using an object (here it is an element rather than a pointer or reference) as a function return value, if the same type is used to receive the return value, the copy constructor will be executed (this will involve the removal and retention of anonymous objects, because the returned objects of the function are anonymous objects ).
2. Example of copying the constructor call Method
# Include
Using namespace std;
Class Location
{
Private:
Int x;
Int y;
Public:
Location ()
{
Cout <"No parameter constructor executed" <endl;
}
Location (int x, int y)
{
This-> x = x;
This-> y = y;
Cout <"the constructor with parameters is executed" <endl;
}
Location (const Location & location)
{
This-> x = location. x;
This-> y = location. y;
Cout <"copy constructor executed" <endl;
}
~ Location ()
{
Cout <"x =" <this-> x <", y =" <this-> y <"destructor executed" <endl;
}
};
/* Simulate copy constructor call method 3 */void setLocation (Location location)
{
Cout <"setLocation () global function..." <endl;
}
/* Simulate copy constructor call Method 4 */
Location getLocation ()
{
Cout <"getLocation () global function..." <endl;
Location location (100,200 );
Return location;
}
/* Call the copy constructor */int main ()
{
/* Copy the constructor call method 1 */
Cout <"############## method 1 ################" <endl;
Location loc1 (1, 2 );
Location loc2 = loc1;
/* Copy the constructor call method 2 */
Cout <"############## method 2 #################" <endl;
Location loc3 (10, 20 );
Location loc4 (loc3 );
/* Copy constructor call method 3 */
Cout <"############## method 3 #################" <endl;
Location loc5 (5, 10 );
SetLocation (loc5 );
/* Copy the constructor call Method 4 */
Cout <"############## Method 4 #################" <endl;
/* After getLocation () generates an anonymous object and assigns it to loc6, the anonymous object executes the Destructor and destroys the object */
Location loc6;
Loc6 = getLocation ();
/* GetLocation () generates an anonymous object and assigns it to loc7. The anonymous object is reset and directly converted to a new object */
Location loc7 = getLocation ();
}
7. constructor Summary
When no constructor is defined in the class, the C ++ compiler defines a non-argument constructor by default, and the function body is empty.
When any Constructor (including the copy constructor) is defined in the class, the C ++ compiler will not define the default constructor for us. That is to say, we must use the constructor.
By default, C ++ provides a copy constructor that points to a shortest copy. It only copies the values of simple member variables.
The C ++ compiler will not provide the copy constructor for me only after we write the constructor. If we do not write the constructor, the C ++ compiler will always provide the default copy constructor.
Iii. destructor
1. Definition and call method of destructor
Definition: A special member function can be defined in the C ++ class to clear objects and release the memory allocated in objects. This special method is called destructor.
Call: when the object life cycle ends, the Destructor is automatically called by the C ++ compiler.
2. Use of destructor
The Destructor is usually called before the end of the object lifecycle. At this time, we will release the heap memory we created in the object to ensure the rationality of the program.
# Define _ CRT_SECURE_NO_WARNINGS
# Include
Using namespace std;
Class Student
{
Private:
Char * name;
Int age;
Public:
Student (char * name, int age)
{
/* Allocate heap memory in the constructor */
This-> name = (char *) malloc (sizeof (name) + 1 );
/* Initialize the member variable */
Strcpy (this-> name, name );
This-> age = age;
Cout <"constructor executed..." <endl;
}
~ Student ()
{
If (this-> name! = NULL)
{
/* Release heap memory in the Destructor */
Free (this-> name );
This-> name = NULL;
This-> age = 0;
}
Cout <"destructor executed..." <endl;
}
Void print ()
{
Cout <this-> name <"=" <this-> age <endl;
}
};
Int main ()
{
Student stu ("Wang Gang", 21 );
Stu. print ();
Return 0;
}
4. constructor and destructor of multiple objects
1. object initialization list
When we have a class member, it is a class, and this member has only one constructor with parameters, and there is no default constructor, We need to initialize this class member at this time, you must call the constructor with parameters for this class member. You can use this constructor to initialize the object when defining the member, but we want to perform dynamic initialization, the member needs to dynamically accept external data, so the object initialization list concept is introduced.
2. The class member is const modified.
When a class member is modified by const, the class member can be initialized when the variable is defined or when the object initialization list is used.
3. object initialization example
Press Ctrl + C to copy the code
Press Ctrl + C to copy the code
4. execution sequence of constructor and destructor
When a member in a class is an object of another class, the constructor of the member variable is called first, and the call sequence is consistent with the definition sequence of the member variable. After all the constructor of the member variables are executed, call the constructor of the class.
The execution sequence of the Destructor is "Inverted", that is, the first is opposite to the execution sequence of the constructor.
5. Copy the deep copy and shortest copy of the constructor.
1. Execution principle of copy constructor
There are four calling methods for the copy constructor. When we do not write the copy constructor, C ++ writes the copy constructor by default, the function body implements copying the values of simple member variables. This default COPY method is called shortest copy, that is, simply copying the value of the member variable to another object.
2. Thrown out of the deep copy Problem
When our member variables are a group of heap memory dynamically allocated, C ++ copies the member variable value for the copy constructor we write by default, the copy will also point to the heap memory allocated by the original object. When we release the heap memory in the destructor, the program crashes because of two destructor (one is that the original object releases the heap memory, and the other is that the copy object releases the heap memory.
3. Example of deep copy code
# Define _ CRT_SECURE_NO_WARNINGS
# Include
Using namespace std;
Class Student
{
Private:
Char * name;
Int age;
Public:
/* No parameter constructor */
Student ()
{
Cout <"No parameter constructor executed..." <endl;
}
/* Constructor with parameters */
Student (char * name, int age)
{
/* Allocate heap memory in the constructor */
This-> name = (char *) malloc (sizeof (name) + 1 );
/* Initialize the member variable */
Strcpy (this-> name, name );
This-> age = age;
Cout <"the constructor with parameters is executed..." <endl;
}
/* Copy the constructor */
Student (const Student & student)
{
/* Re-allocate memory */
This-> name = (char *) malloc (sizeof (student. name) + 1 );
/* Initialize the member variable */
Strcpy (this-> name, name );
This-> age = age;
Cout <"copy constructor executed..." <endl;
}
/* Destructor */
~ Student ()
{
If (this-> name! = NULL)
{
Free (this-> name );
This-> name = NULL;
This-> age = 0;
}
Cout <"destructor executed..." <endl;
}
Void print ()
{
Cout <this-> name <"=" <this-> age <endl;
}
};
Int main ()
{
Student stu1 ("Wang Gang", 22 );
/* Copy the constructor to execute the command. If you perform a deep copy when creating a copy, no structure issue occurs */
Student stu2 = stu1;
Return 0;
}