12. C ++-constructor and destructor call sequence, const member function, const object, 12. cconst
The Calling sequence of the constructor when a single object is created
1.First, determine whether the class of the object has a parent class.First call the constructor of the parent class
2.Checks whether the object member is a member of other classes.Call the constructor of a member variable(The call sequence is the same as the Declaration Order)
3.Last called objectConstructor of the class itself
After a single object is deregistered, the calling sequence of the Destructor is opposite to that of the corresponding constructor.
Refer to the following example to create two classes of Member, Test, and the Tesrt Member contains members of the Member class:
#include <stdio.h>class Member{ const char* ms;public: Member(const char* s) { printf("Member(const char* s): %s\n", s); ms = s; } ~Member() { printf("~Member(): %s\n", ms); }};
class Test{ Member mA; Member mB;public: Test() : mB("mB"), mA("mA") { printf("Test()\n"); } ~Test() { printf("~Test()\n"); }};Member gA("gA"); int main(){ Test t; return 0;}
Run print:
Member(const char* s): gAMember(const char* s): mAMember(const char* s): mBTest()~Test()~Member(): mB~Member(): mA~Member(): gA
Const member functions
To demonstrate the encapsulation of objects, C ++ introduces const member functions in the class.
- In the cosnt member functionCan only be calledConst member functions
- In the const member functionCannot be directly modifiedMember variable value
- OnlyMutable ModificationThe const member function can be modified.
- If you use a const-modified function, this functionMust be a member function of the class.
Const member function definition, which is in the function declarationRightmostInclude the const keyword, for example:
class Test{pbulic: int func(void) const;}int Test::func(void) const{ }
Const object
- Member variables of the const objectNot AllowedChanged,
- Const objectCan only be calledThe const member function, rather than the const object, can access the const member function.
- The const object is a concept in the compilation phase and is invalid during runtime.
Const object definition, which is declared in the objectLeftmostInclude the const keyword, for example:
class Test{pbulic: int func(void) const;}int Test::func(void) const{ }const Test t;