01C + + review Class & object / constructor / copy constructor / operator overload / destructor

Posted by arya202 on Thu, 10 Mar 2022 11:13:17 +0100

1, C + + classes & objects

C + + adds object-oriented programming on the basis of C language, and C + + supports object-oriented programming. Class is the core feature of C + +, which is usually called user-defined type.

Class is used to specify the form of an object. It contains data representation and methods for processing data. The data and methods in a class are called members of the class. Functions in a class are called members of the class.

1. Define C + + classes

Defining a class is essentially a blueprint for defining a data type. This does not actually define any data, but it defines what the name of the class means, that is, it defines what the object of the class includes and what operations can be performed on this object.

Class definition starts with the keyword class, followed by the name of the class. The body of the class is contained in a pair of curly braces. Class definition must be followed by a semicolon or a declaration list. For example, we use the keyword class to define the Box data type, as shown below:

class Box
{
   public:
      double length;   // Length of box
      double breadth;  // Width of box
      double height;   // Height of box
};

The keyword public determines the access properties of class members. Within the scope of a class object, public members are accessible outside the class. You can also specify that the members of the class are private or protected.

2. Defining C + + objects

Classes provide a blueprint for objects, so basically, objects are created based on classes. Declaring objects of classes is like declaring variables of basic types. The following statement declares two objects of class Box:

 Box Box1;          // Declare Box1, type Box
 Box Box2;          // Declare Box2, type Box

Objects Box1 and Box2 have their own data members.

3. Member data access

Class can use the direct member access operator (.) To visit. To better understand these concepts, let's try the following examples:

 
using namespace std;
 
class Box
{
   public:
      double length;   // length
      double breadth;  // width
      double height;   // height
};
 
int main( )
{
   Box Box1;        // Declare Box1, type Box
   Box Box2;        // Declare Box2, type Box
   double volume = 0.0;     // For storage volume
 
   // box 1 details
   Box1.height = 5.0; 
   Box1.length = 6.0; 
   Box1.breadth = 7.0;
 
   // box 2 details
   Box2.height = 10.0;
   Box2.length = 12.0;
   Box2.breadth = 13.0;
 
   // Volume of box 1
   volume = Box1.height * Box1.length * Box1.breadth;
   cout << "Box1 Volume of:" << volume <<endl;
 
   // Volume of box 2
   volume = Box2.height * Box2.length * Box2.breadth;
   cout << "Box2 Volume of:" << volume <<endl;
   return 0;
}

It should be noted that private members and protected members cannot use the direct member access operator () To access directly.

4. Member function of class

Class member functions refer to those functions that write definitions and prototypes inside the class definition, just like other variables in the class definition. The member function of a class is a member of a class. It can operate any object of the class and access all members in the object.

Let's take a look at the previously defined class Box. Now we want to use the member function to access the members of the class instead of directly accessing the members of these classes:

{
   public:
      double length;         // length
      double breadth;        // width
      double height;         // height
      double getVolume(void);// Return volume
};

Member functions can be defined inside the class definition, or they can be defined by using the range resolution operator::. A member function defined in a class definition declares the function inline, even if the inline identifier is not used. Therefore, the Volume() function can be defined as follows:

{
   public:
      double length;      // length
      double breadth;     // width
      double height;      // height
  	//The member function getVolume() here is an inline function
      double getVolume(void)
      {
         return length * breadth * height;
      }
};

You can also use the range resolution operator:: outside the class to define the function, as shown below:

{
    return length * breadth * height;
}

Create a class in C + +, which will certainly include constructor, destructor, copy constructor and overload assignment operation.

2, Class constructor

The constructor of a class is a special member function of a class, which is executed every time a new object of the class is created.

The name of the constructor is exactly the same as the name of the class, and will not return any type or void. Constructors can be used to set initial values for some member variables.

Constructors include default constructors and constructors with parameters.

1. Default constructor

The default constructor has no return value and no parameters. Here is an example of the default constructor:

{
   public:
      void setLength( double len );
      double getLength( void );
      Line();  // This is a constructor
 
   private:
      double length;
};
 
// Constructor definition
Line::Line(void)
{
    cout << "Object is being created" << endl;
}

2. Constructor with parameters

The constructor with parameters can be understood as the default constructor with parameters, so that the object will be given an initial value when it is created, as shown in the following example:

{
   public:
      void setLength( double len );
      double getLength( void );
      Line(double len);  // This is a constructor with parameters
 
   private:
      double length;
};
 
// Constructor definition with parameters
Line::Line( double len)
{
    cout << "Object is being created, length = " << len << endl;
    length = len;
}

3. Use the initialization list to initialize fields

Use the initialization list to initialize fields:

{
    cout << "Object is being created, length = " << len << endl;
}

The above syntax is equivalent to the following syntax:

{
    length = len;
    cout << "Object is being created, length = " << len << endl;
}

Suppose there is a class C with multiple fields X, Y, Z, etc. that need to be initialized. Similarly, you can use the above syntax. You only need to separate different fields with commas, as shown below:

{
  ....
}

The difference between initialization list initialization and constructor initialization:

(1) Initialization list initialization is the explicit initialization of class members, while constructor initialization is the assignment of accumulated members;

(2) For member variables of built-in types, the performance and results of initializing with initialization list and initializing with constructor are the same.

(3) For member variables with non built-in types, because the data member object of the data member of the class type has been constructed before entering the function body, that is, construct the object in the member initialization list and call the constructor. After entering the function body, assign the value to the constructed class object, Another assignment operator is called to complete (if not provided, the default member assignment behavior provided by the compiler is used). In order to avoid double construction, it is recommended to use class constructor to initialize the list.

However, there are many occasions when constructors with initialization lists must be used. For example, a member type is a class without a default constructor. If no display initialization is provided, the compiler implicitly uses the default constructor of the member type. If the class does not have a default constructor, the compiler will fail to call the default constructor. Another example is const members or members of reference types, because const objects or reference types can only be initialized and cannot be assigned.

The basic built-in types of C + + include arithmetic type and null type. Arithmetic types include integer (integer, character, Boolean) and floating point. Empty type refers to void type

3, Copy constructor for class

1. Copy constructor definition

Copy constructor is a special constructor, which is also used to initialize class members and allocate storage space for object construction. The name of the function must be consistent with the name of the class, and there is no return type. Its only parameter is a reference variable of this type, which is const type and immutable.

The prototype of the copy constructor is as follows:

For a class X, if the first argument of a constructor is one of the following:

   const & X;
   volatile & X;
   const volatile & X;

If there are no other parameters or other parameters have default values, this function is a copy constructor, as follows:

    X::X(& X, int=1); 
    X::X(& X, int a=1, int b=2);

2. Copy constructor implementation

{ 
public: 
    Date(int year = 1995,int month = 12,int day = 8) // Constructor with parameters 
        :_year(year) , _month(month) , _day(day) //Initialization list initialization
    { 
        cout << "date()Constructor"<< this << endl; 
    } 
    Date(const Date& d)// copy constructor  
        :_year(d._year) , _month(d._month) , _day(d._day) 
    { 
        cout << "date(&d)" << this << endl; 
    }
private: 
    int _year; 
    int _month; 
    int _day; 
};

4, Class

1. Overload the definition of assignment operator

Overload assignment operator is a special assignment operator, which is usually used to assign existing objects to other objects of the same type.

The prototype of overloaded assignment operator is as follows:

2. Implementation of overloaded assignment operator

{
	cout << "operator= Assignment operator overload " << this << endl;
	if (this != &d) // Determine whether you assign values to yourself
	{
		_year = d._year;
		_month = d._month;
		_day = d._day;
	}
	return *this;
}

Note: the return value of the overloaded assignment operator is a reference.

3. Call of copy constructor and overloaded assignment operator

When the object of the class needs to be copied, the copy constructor will be called. The copy constructor is called when:
An object is passed into the function body by means of value transfer;
An object is returned from a function by passing a value;
An object needs to be initialized by another object.

If an object assigns another existing object to it while declaring it, the copy constructor will be called; If an object already exists, and then another existing object is assigned to it, the overloaded assignment operator is called.

     CTest obj;
     CTest obj1(obj); // Call copy constructor
     obj1 = obj; // Call overloaded assignment operator

4. Deep copy and shallow copy

If there is no explicit declaration in the class, the compiler will automatically generate the default copy constructor and overload assignment operator. The default copy constructor and assignment operator are "share copy", which simply copies the fields and assigns the values to the values to be copied one by one. Therefore, if the object contains dynamically allocated memory, we need to rewrite the copy constructor and overload the assignment operator to realize "deep copy" to ensure the integrity and security of the data.

For example, member variables within A class need to dynamically open up heap memory. If shallow copy is implemented, that is, the value in the object is completely copied to another object, such as A=B. At this time, if A member variable pointer in B has applied for memory, the member variable in A also points to the same block of memory. There is A problem: when B releases the memory (e.g. destruct), the pointer in A is A wild pointer, and A running error occurs.

Deep copy and shallow copy can be simply understood as: if a class has resources (heap, or other system resources), when the object of this class is copied, the resources will be reallocated so that the object has different resources, but the content of the resources is the same, this process is deep copy; On the contrary, without reallocating resources, the two objects have common resources and can access the resources at the same time, that is, shallow copy.
Shallow copy is just a copy of the pointer. After copying, the two pointers point to the same memory space. Deep copy not only copies the pointer, but also copies the content pointed by the pointer. The pointer after deep copy points to two different addresses.

5, Class destructor

Class destructor is a special member function of a class, which will be executed every time the created object is deleted.
The name of the destructor is exactly the same as that of the class, except that it is prefixed with a tilde (~), which will not return any value or take any parameters. Destructors help to free resources before jumping out of the program (such as closing files, freeing memory, etc.).
The following examples are helpful to better analyze the concept of constructors:

{
   public:
      void setLength( double len );
      double getLength( void );
      Line();   // Constructor declaration
      ~Line();  // Destructor declaration
 
   private:
      double length;
};
 
//Constructor definition
Line::Line(void)
{
    cout << "Object is being created" << endl;
}
//Destructor definition
Line::~Line(void)
{
    cout << "Object is being deleted" << endl;
}

Three rules if the type clearly defines one of the following member functions, the programmer must write the other two member functions into the type, that is, the following three member functions are indispensable:

(1) Destructor

(2) copy constructor

(3) Overload the copy assignment operator

Transfer from https://blog.csdn.net/sinat_33924041/article/details/83621017

Topics: C++