1. Sub-objects
When an object is a member of another class, it is called a sub-object of this class. A sub-object uses an object as a data member. When an object member exists in a class, the constructor of this class must contain the initialization of the Child object (the member initialization list is placed behind the constructor and separated by a colon. The member initialization list consists of one or more options. Multiple options are separated by commas. The options in the member initialization list can be used to initialize the child object or other data members of this type ). Example:
# Include <iostream>
Using namespace STD;
Class M
{
Public:
M (int I, Int J)
{
M1 = I;
M2 = J;
}
Void print ()
{
Cout <M1 <"," <m2 <Endl;
}
PRIVATE:
Int M1, M2;
};
Class N
{
Public:
N (int I, Int J, int K): m (I, j)
{
N = K;
}
Void print ()
{
M. Print ();
Cout <n <Endl;
}
PRIVATE:
M m;
Int N;
};
Void main ()
{
M M1 (3, 9 );
M1.print ();
N N1 (10, 20, 30 );
N1.print ();
}
2. Heap object
Objects Created at any time as needed during the program running are called heap objects. A heap object is a variable placed in the memory heap area and can be deleted at any time as needed.
Create a heap object using the new operator in the following format:
New type specifier (Initial Value List)
The expression of the new operator is a pointer. It is used to assign an address value to an object. The type of the object is specified by the type specifier. The object can be a class object, it can also be a type of variable. The initial value list shows the initial value of the object. If it is omitted, the created object uses the default value. When an object is created using the new operation, the system automatically calls the constructor of this class.
1) int * P; P = new int (8 );
2) A * pA; Pa = new A (3, 7 );
3) int * P; P = new int [10]; use the new operator to create an array. P is a pointer to the first element of a one-dimensional array;
4) A * PTR; PTR = new A [5]; same as 3;
Use Delete to release objects
The format is as follows:
1) Delete pointer name;
2) Delete the Delete [] pointer name of the array object;