The object is not suddenly established, and the object must be created at the same time as the parent class and the object contained therein. C + + follows the following order of creation:
(1) If a class is specific to the base class, the default constructor for the base class is executed.
(2) Non-static data members of the class, created in the order in which they are declared.
(3) Executes the constructor of the class.
That is, when a class is constructed, its parent class is constructed, then the class member is created, and the constructor of itself is called.
Let's look at an example.
Copy Code code as follows:
Class C
{
Public
C () {printf ("c\n");}
Protected
Private
};
Class B
{
Public
B () {printf ("b\n");}
Protected
c C;
Private
};
Class A:public B
{
Public
A () {printf ("a\n");}
Protected
Private
};
int main ()
{
A A;
GetChar ();
}
Let's analyze It. First defines 3 classes a B C, where a inherits from B, constructs a in the main function, because a is inheriting B, so it constructs B, then Class B has a member C class, so the C class is first constructed, then B, and finally a.
To see an example, the above should be a bit:
Copy Code code as follows:
Class C
{
Public
C () {printf ("c\n");}
Protected
Private
};
Class B
{
Public
B () {printf ("b\n");}
Protected
Private
};
Class A:public B
{
Public
A () {printf ("a\n");}
Protected
c C;
Private
};
int main ()
{
A A;
GetChar ();
}
Didn't change much, just added a C member in a, and b got rid of it.
Also constructs a in main, a inherits from B, so constructs B first, then constructs the data member C of a itself, and finally calls the constructor of the a itself.
Everyone here should understand the details of the construction.
Next look at the sequence of the destructors:
(1) invokes the destructor of the class.
(2) Destroy data members in the reverse order of creation.
(3) If there is a parent class, the destructor of the parent class is invoked.
Let's look at one example:
Copy Code code as follows:
Class C
{
Public
C () {}
~c () {printf ("c\n");}
Protected
Private
};
Class B
{
Public
B () {}
~b () {printf ("b\n");}
Protected
Private
};
Class A:public B
{
Public
A () {}
~a () {printf ("a\n");}
Protected
c C;
Private
};
int main ()
{
A A;
return 0;
}
The process is that, at the end of the main function, A is destroyed, the destructor of a is called first, the data member C of a is destroyed, and the parent class B of a is finally destroyed. is actually the reverse of the order in which they were created.
Well, here I believe that we have understood the mysteries of structural deconstruction!