C ++ 100 tips (some may not belong to C ++)

Source: Internet
Author: User
Tags bitset

This was before (when ?) Parts of the Notes (it should be when reading C ++ primer) are not necessarily correct, but they are for reference ~~

A better learning method:
<1>. Learn through instances one by one (it can be an instance in each chapter, starting with a simple example, and finally becoming a perfect example with high reference value)
<2>. Record tips as follows as a memo (you can describe it in your own language to deepen your understanding and image)
<3>. Without it, hand-cooked.

1. extern "C": The C ++ compiler can recognize it. The labeled part will be compiled in C mode.
I personally think that the function labeled with extern "C" will have two aliases, so this function can be referenced in both C ++ and C code.

2. We can do this when defining enumeration:
Typedef Enum
{
Enum1 = 0,
Enum2,
} My_enum;
That is, assign a value to the first enumeration, and then accumulate 1 in sequence.

3. Note: C does not support function overloading at the compilation level. Therefore, only one overload function in C ++ can be described by extern "C.

4. Functions declared as inline are not necessarily embedded into references during compilation. The Inline keyword only provides suggestions for the compiler.
Benefits of inline functions:
You can define a common operation or code as a function to facilitate maintenance and modification, and to facilitate reading and understanding. Therefore, inline functions are generally short and concise!
Unlike non-inline functions, inline functions must be defined in each text file that calls the function. And must be the same. So the best way is to define it in the header file.

5. Difference Between Reference and pointer. The reference cannot be blank or be changed ~~, The advantage is that the operation is intuitive. If a pointer is used, the Code may be lost. Especially when the operator is overloaded.

6. The following statement
Void AAA (INT [10]);
It is viewed by the C ++ compiler
Void AAA (int *);
Therefore, the following three statements are equivalent:
Void AAA (INT [10]);
Void AAA (int *);
Void AAA (INT []);

7. c struct is only a collection of variables. It cannot hide data or encapsulate operations. The difference between struct and class in C ++ is that struct is public by default.

8. Advantages of the enumeration type: Do not assign numeric constants (integers) to enumeration variables. This prevents misoperation (for example, when you use an enumeration variable as a parameter, the value of the input variable is limited );
Macro definitions can be replaced by enumeration types, such:
Enum {
Max_len = 100,
Type1 = 1,
Type2 = 2
};

9. Two struct definition methods:
When the struct is defined in the header file or a module and needs to be used by other modules, it is best to use typedef:
Typedef struct _ struct_a {
Int I;
Int J;
} Struct_a, * pstruct_a;
When the struct only needs to be used in this module, you can directly define and declare:
Struct struct_s {
Int I;
Int J;
} Mystruct1, mystruct2, mystructs [100], * pmystruct;

10. Why use the volatile Keyword: the compiler optimizes the registers of program variables. For example, a frequently used variable may be stored in a register. Volatile variables may be controlled by the compiler.

The field is modified. For example, the field is a register-related value, and is interrupted or always updated. At this time, tell the CPU that the variable cannot be optimized, and read the original value every time.
Volatile usage is similar to const usage. Volatile and const are modified by the variables on their right.

11. Complex and pair types:
# Include <complex >|# include <utility>
Using: complex <double> r1 (11, 11.22 );
Pair <string, string> P1 ("AA", "BB ");
Tip: You can use typedef pair <string, string> PP;

12. Proper pointer writing: char * cursor, CH2; instead of char * cursor, ch2.

13. Why define macros or constants?
Easy to modify; prevent misoperations (for example, if (maxlen = 1); clear meaning (a name can be used)

14. The reference must be initialized to an object. Once specified, you cannot point to other objects. Note the features of const reference. The address of the referenced object, which is an alias of the object. Unaddressable values

, Such as a text constant, the compiler will generate a temporary object, but the user cannot access this object.
See the reference below:
Const int ival = 1024;
Const int * const & pi_ref = & ival;
In C ++, the reference type is mainly used as a function form parameter.
The reference must point to an object. If: Char & Ch = 0;
Then the compiler translates it into: Char temp = 0; char & Ch = & temp;

15. An important error source:
In C ++, classes are just smart data structures. When an object is copied to another object and the object contains one or more pointers (the pointer address overwrites the pointer, instead of copying the pointer content )....

16. You can use an array (or part) to initialize a vector, for example:
Int AA [8] = {1, 1, 1, 1, 5, 6 };
Vector <int> V (AA + 3, AA + 8 );
Vector has two usage modes: built-in array usage and STL usage.
Learning STL design patterns and thinking methods is not a bad thing ~~

17. member function pointer r (t ::*)(...)

18. memory pool available for each program execution. This available memory pool is called the free store or heap of the program ). Dynamic memory allocation.

19. c ++ has the bitset operation, and # sorted ed <bitset> is very easy to use. You can try it.

20. The forced conversion in the C ++ framework is different from that in C. The type conversion is called cast, which has the following cast:
Static_cast:
Dynamic_cast:
Const_cast:
Reintepret_cast:
Any non-const class pointer can be converted to void * type pointer.

21. The programmer must explicitly tell the compiler to stop executing the statements in the switch. Break. In most cases, a comment should be provided for case statements that intentionally omit the break tag. Our program should not only be able to compile and execute, but also

Later programmers responsible for modification and expansion should also be understandable.
It is also necessary to omit break. When we use a collection:
Switch (I ){
Case 1: Case 2: Case 3:
DO 123;
Break;
Case 4: Case 5:
Do 45;
Break;
Case 6:
Break;
Default:
Do default;
}

22. variable parameters, such:
Printf (const char *,...);
Print (...);
For more information about Variable Parameter resolution, see ~~

23. The maximum use of function pointers is for callback design. This usually involves "function registration ".
For a function such as void ff (void) {retrun ;}
Define a function pointer void (* PFF) (void );
PFF = ff; PFF = & FF are optional.
Function pointer array ~~

24. The namespace definitions of different program text files can be accumulated. Namespace supports nesting.
In C ++, an unnamed namespace can be used to declare an object partial to a certain file. For example:
Namespace {
Void func (void ){};
}
In the c file, the solution is to add the static prefix to the function definition.

25. All components in the Standard C ++ library are declared and defined in a namespace called STD. The functions, objects, and class templates declared in the standard header file are declared in the namespace STD.

26. About the function template. Function templates provide an algorithm used to generate various types of function instances. Parameterize all or part of the function interfaces. Similarly, class templates are similar.

27. c ++ containers include sequence container and associative container;
The former is list, vector, and deque.
The latter is map, set, multimap, and Multiset.
Containers support comparison operators.

28. To improve efficiency, vector does not have to increase its length every time it inserts an element. It needs to increase its own length, which is always allocated more in advance. Therefore, it has two attributes: capacity, but size. Actual table

It is exponential growth.
When traversing a sequential container: iterator can perform any pointer operation, because sequential containers support Random Access to the memory continuously. For example: iterator ++; iterator --; iterator + n
For memory discontinuous containers such as list: iterator cannot perform iterator +/-N operations, but can perform ++/-- Operations (Operator Overloading should be performed)

29. performance problem: when the length of data elements is relatively small, the efficiency advantage of vector is obvious (insert), while list is more advantageous. The growth mechanism of vector is: the size of each allocation needs to be twice, and then the old data is copied to the new allocation.

. The overhead of list is mainly memory allocation. Data allocation is required for every insert, even if the data element is small. To improve the efficiency of the vector, when the length of the data type is large, you should indirectly store

Complex data types (this is obviously a very effective practice ).

30. iterator: a lot of thing !!

31. parent classes and child classes can be converted to each other. However, it is not recommended to forcibly convert them from parent classes to child classes to avoid unknown operations.

32. Compile a simple C ++ program to compile it into EXE and use the disassembly software to disassemble it. It can analyze the internal implementation of C ++ and some naming rules of C ++ compiler. For example, the name of "cout <" in the compiler is

"Ostream: Operator <"

33. variables defined in the try {} module cannot be referenced in the Catch Block due to locality. A good programming mode is try {} catch (a) {} catch (B ){}...
To catch all exceptions, catch (...) {} (similar to variable parameters)

34. Understand the exception throw mechanism of c ++. The exception throw mechanism can be understood as a dynamic function call. The difference is that the function call is determined during compilation, but the throw is completely unknown. If an error is detected, the throw statement is called.

The statement copies an exception object, finds the corresponding catch statement, and expands the stack layer by layer to find the corresponding catch statement. If not, the default terminate function is called. Catch (exp) is equivalent

Function. If it is written as catch (exp & exp), it is equivalent to the transfer address. In fact, the latter is quite recommended, because it can prevent large overhead for copying abnormal objects, and also facilitate modifying exp objects for secondary throws. If you do not use

In the second throw of catch (exp) {exp. value = 1; throw;} in the following code, the throwing object has not actually changed. Terminate calls the program in the abort () function by default.

35. Exception specification: If I write a library with many functions, how do database users know which functions will throw exceptions? The exception specification provides a solution that lists the possible throws of a function with the function declaration

Exception. Format: void POP (Int & Value) Throw (poponempty); this limits that this function can only throw the poponempty function at runtime; otherwise, unexpected ()-> terminate () will be called () forcibly stop the program. However

To clarify a few points, the function throws an exception that does not conform to the exception specification but solves it internally, which is not a violation. Or there is a statement that throws an exception but will never be executed, the compiler does not report errors.

All declarations must be included.

36. exception and Program Design: Although C ++ supports exceptions, it does not mean that exceptions must be used. The program can also use multiple troubleshooting methods, such as: Return Error Codes and partial processing (using if statements) and so on. Everything is realistic.

37. About assert macro:
# If defined ndebug
# Define assert (condition) (void) 0)
# Else
# Define assert (condition) _ assert (condition), # condition, _ file __, _ line __)
# Endif
It is worth learning: _ assert itself is a macro, and a macro is encapsulated outside to define it differently from the compilation options. This is a common method of switch quantity.

38. The assert always appears in the debugging version and does not appear in the release version. So we need to be vigilant. Some errors in the debug version can be simply diagnosed using assert, because it is only visible to developers; but in the release version, either

Errors are not allowed, or you can set up code to correct errors. You must fix the errors diagnosed by assert before release.

39. generally, the compiler uses EBP to indicate the current active stack frame. If main ()-> Add (); then the stack frame is the stack frame of main first and then the stack frame of ADD, EBP points to the beginning of the add stack frame, esp points to the top of the stack, and the local variables in the Add function are parsed.

It is a fixed offset relative to EBP. Because the stack grows down, most of them are represented in the form of EBP + N (very interesting, when you press the stack, ESP is actually reduced ). When the compiler compiles a function, it will add some code at the beginning

Create and initialize a stack consumer for it. The code is called Prologue. Similarly, it also puts code at the end of the function to clear the stack consumer, these codes are called epilogue ).
Generally, the preface is as follows:
Push EBP; Save the original stack token pointer to the stack
MoV EBP, esp; activate a new stack token
Sub ESP, 10; subtract a number to point ESP to the end of the stack consumer: 10 refers to all the local variables and temporary object sizes used by the function. During compilation, the compiler knows the type and volume of all local objects in the function ".
The conclusion is exactly the opposite of the preface. It must remove the current stack shard from the stack:
MoV ESP, EBP
Pop EBP; activate the stack callback of the Main Function
RET; return the main call function (the address of the subsequent command is automatically pushed into the stack when the call command is executed, and RET is the opposite)

40. Class Members can only be initialized in the constructor. If Explicit initialization is not performed, a default initialization method is provided. (Static members are initialized before construction because they are equivalent to global variables)
In addition, the "initialization" process such as a = 1; B = 2; inside the constructor is not a real initialization, but a value assignment. The real Initialization is a list of parameters. That is, the class has been initialized before executing the statements in the constructor.

Object.

41. The Decompilation function of vc6.0 is amazing! If you want to study the C ++ Compiler Principle, for example, how does one support classes? Compile a program and decompile it. Compared with C, C ++ has a huge and intelligent performance, but we must

It is clear that these new features of C ++ depend entirely on the power of the compiler and are compiled to the machine code level (Assembly level). c is no different from C ++. Why is C a semi-machine language, because its syntax concept is

Without too many extensions, C ++ has many abstract concepts. The simplest concept of a class is that you define a Class A {int A, int B} like this and generate an instance a aa. For the compiler, {a aa }={ int

AA. A, int AA. B }. In a sense, C ++ simplifies C (increases semantics, reduces programming difficulty) and then gives complexity to the compiler.

42. When defining another class, we usually put the public area in front and the private area in the back.

43. Be sure to understand the compilation process and strictly distinguish between compilation and connection, so that you can analyze the cause accurately without making mistakes during program writing. For example, declarations affect compilation and definitions affect connection.

44. This is the case after a class is compiled. It is a push function body. These functions add a pointer to this object. For example:
Code:
Class {
Public:
Int;
Void add () {A ++ ;}
}
After compilation, a function similar to add (A * This) {(* (int *) (char *) This-4) ++} will appear, because the offset between the member variables in the class and the address indicated by the class pointer is fixed, the operations on the member variables are also

That is, the operation is performed on an offset of a certain type. As for static member variables, they are global variables at all, but only the prefix is added to the name.
We can think that the object of a class is a function + static variable, and the object is a struct. That is, a bunch of structs share a group of functions.
Deep understanding: Each Class Object maintains a copy of the class data member, but the member function only has one copy.

45. Limitations of the const member function: if the class contains pointer members, the const member function can modify the objects referred to by the pointer (the compiler will not report an error)
In addition, const member functions can be overloaded by functions with the same name as non-const functions.
Objects declared as const can only call member functions modified by const.

46. mutable modifier. Compared with const, it is used to resist const's "overbearing and pedantic corruption ".
The const and volatile member functions actually modify the this pointer. Because this is modified, all data members are actually modified. Therefore, when the const function returns a member, const this-> memberx is returned.

47. if each member function returns a reference to (* This), operations on an object can be connected to a string, just like this:
Test.int (). Move (1, 2). Show (); // the call to the three functions is completed in one statement.

48. as a special case, the ordered const static data member can be initialized with a constant in the class body.
For example:
Static const int namesize = 16;
Static const char name [namesize];

49. an Application Mode of function pointers: There are a lot of operations, they have similar interfaces, and now there is another function B that needs to call these operations, then we can pass the operator an to B as a pointer.
Of course, function pointers are of great use and can be used in many effective design modes to effectively increase efficiency and reduce structural complexity.
Another question is why the member function pointer cannot be equivalent to a function pointer defined in the same structure outside the class. In fact, this is the simplest, because the member function contains a this pointer. A member function must first be bound to a pair

In order to obtain the pointer of the called object, you can call the member function referred to by the pointer. Although common function pointers and member function pointers are called pointers, they are different things.

50. The class member pointer and class member function pointer should be a few wordings.
Class A () {public: int A; void F (){}}
The member pointer declares: int A: Pa = & A:;
Member function pointer Declaration: void (A: * PF) () = & A: F;
If there is a ca today, the pointer can be used as follows:
Int I = Ca. * pA; (ca. * PF) (); for the internal process of the compiler, see relevant books ~~
The void (A: * PF) () is easy to understand. It tells the compiler that the PF function must include a pointer parameter of a * This, and (ca. * PF), Ca. indicates that compilation is passed into the function & Ca.

51. The pointers of static class members are the same as those of non-class members. It is very easy to understand this point from the compiler perspective.

The difference between Union in 52. c ++ and union in C. Union is usually used in a way similar
{
Int ID;
Union value {
....
}
. There is a special union called anonymous union. Anonymous Union removes a layer of member access operators. Therefore, anonymous Union cannot have private or protected members, nor can it define member functions. Union

Must be declared in an unnamed namespace (or declared as static)

53. bitset template. c ++ recommends that bitset class templates be used in applications that use bitset operations. bitset operations can usually be associated with enumeration and constant definitions, because no one is willing to remember what each character means.

54. The comparison between local classes and Nested classes is rarely used at ordinary times, so you don't need to know them carefully, but you need to realize that the C ++ compiler supports these properties.

55. We recommend that you use the default parameter constructor because it can reduce the number of constructor. Do not mistakenly think that if there is no default constructor, the compiler will automatically add it. No.
Another thing that is easy to take for granted is that constructors must be common. In fact, a private constructor has a specific purpose.

56. A small problem. We should never define an object class1 class1 () in this way; just remove the brackets that follow; otherwise, the compiler will regard this as a function declaration. Have you ever made such a low-level mistake?
Also, when we define a constructor, we must call its constructor when defining an object instance, unless a constructor has a default parameter (in this case, the compiler automatically adds the default constructor)
When we need to declare a large number of objects at a time, we certainly hope to have a default constructor. This page is the best reason for providing a default constructor.

57. The Decompilation shows that the VC ++ compiler converts the reference type to a pointer. However, if you use sizeof to obtain the size, it is not the pointer size, but the object size.

58. Copy the constructor. It is very c ++. Its parameters are references to such objects (usually declared as const ).
Note: Even if you do not declare a copy of the constructor, you can still use one object to initialize another for some simple classes. The compiler will execute default initialization by members.

59. destructor: When you dynamically allocate memory or use operating system resources (such as mutex locks, such as handle), The Destructor must exist. However, the function of destructor is not only to release resources. Make full use of its final

This feature must be implemented. The compiler records where a class (within its lifetime) is finally called and inserts its destructor.

60. The C ++ language ensures that the delete operator is not used to delete pointers that do not point to any objects. Therefore, the following judgment is unnecessary: If (PT) delete pt; this judgment is done by the compiler.

61. The power of C ++ lies in pointers. The C ++ disaster is often a pointer. So there are many commercial smart pointers on the market. You can focus on their implementation technologies. However, C ++ itself provides a compact intelligence

What auto_ptr can do is to dynamically allocate objects and automatically clean up objects when they are no longer needed. In view of this fact, when C ++ encounters an exception, the analysis structure of the objects in the stack will be called during the stack expansion process.

Function. But it does not clean up new objects. For example, a = new A ();... delete a; it is very likely that the delete operation has never been executed due to an exception between the two statements. This is a typical case of Memory leakage. Therefore, if the pointer is enclosed

Install it into a class, and then clear the indicated object in its destructor. The problem can be well solved, and delete is not required after new. So we need to move our minds more often ~~

62. When do I need to explicitly call the Destructor? This is because when you delete an object, not only an object is called, but also the heap memory is deleted. Sometimes we don't want this, especially when multiple objects share a block of memory. So

We can call the Destructor without deleting it.

63. Object array initialization:
Account Pols [] = {
Account (...),
Account (...),
Account (...)
}

64. The Decompilation result of VC ++ indicates that a function table is generated after the program is compiled:
Jmp d: D (32 bits address)
JMP...
The commands that jump to the specified function entry are closely arranged in the same way as the interrupt vector. Therefore, when we call a function, we do not directly jump to the function entry, instead, jump to"

Function table "corresponds to the JMP command, and jumps to the target function through the JMP command.

65. VC ++ decompilation indicates that the this pointer of a class member function uses the ECX register instead of the parameter stack method, in fact, the function uses the ECX value as the first temporary variable in the stack at the entry position and stores it at the position of the ebp-4.

66. Impact of the member initialization table on performance. Do not mistakenly think that using a member to initialize a table always improves the performance of the constructor. This depends on the specific situation. Let's first understand what the compiler has done. If a function contains

If there are Class Object members (not just simple objects such as int in C ++), the compiler will generate an implicit initialization table before executing the constructor, the default constructor of the class member is called. Therefore, if a value is assigned to the constructor

It uses a copy constructor with a high overhead. However, for simple variables, you do not need to use members to initialize the list.
In short, for class objects, there is a big difference between initialization and assignment. It doesn't matter, but it seems clearer to use the initialization list. Specifically, the const and reference members must use the initialization list for initialization.
A general rule is to initialize all member objects in the member initialization list.

67. Initialization order: it is irrelevant to the order in the list and related to the member declaration order. If we want to block the initialization by members, declare a copy constructor but do not define it.

68. When reloading the value assignment operator, you should note that it is best not to copy the value on your own, so add an IF (this! = & Copy)

69. The C ++ language cannot effectively return a class object, which is considered a major defect of the C ++ language. Understand this sentence, and think about whether there is a better solution besides the compiler.

70. Operator overload function. In many cases, a reference is returned (in fact, many member functions can also be) for continuous operations. For example, cout <A <B <C <Endl; why can the <operator be called continuously? Because the previous <return

The returned result is cout <; for example: (C = (a + = B). showmenber ();
Only operators in the C ++ predefined operator set can be overloaded. In addition, the meaning of each operator must be predefined.
Some special operators are-> and ().

71. According to the C ++ programming specification, try to make errors occur during compilation and minimize the possibility of errors during runtime. For example, make full use of the language features of C ++. If a variable should not be changed, it is best to declare it as const for compilation.

The compiler can recognize this, so that the compiler can pull it out in case of misoperations or negligence (which is inevitable in a large program. Therefore, good coding habits are very important.

72. how to explain C ++-> OPERATOR: This is a recursive interpretation process. For language elements a->, C ++ first looks for the semantics of A. If a is an object or reference, when you call its member operator> get the returned object, if the returned object is still

Recursion of an object or reference. Until a pointer type is obtained. Then-> it becomes the inner definition semantics of the member.

73. Nesting of template definitions. I was wondering how iterator was implemented. People on the Internet say that templates and operators are used for overloading. Operators are reloaded without having to say that, but the use of templates is still a bit skillful.
First, it is defined in the internal declaration of a class and thrown with the public keyword, for example:
Class {
Public:
Typedef struct _ B {} B;
} Then an object can be defined using a: B;
Second, template nesting, such:
Template <class T> Class {};
Template <class T> Class B {};
B <A <int> is used for definition or declaration. This is what iterator does.

74. Try... catch is easy to use. You can throw a string in the try block, print the string in the Catch Block, and exit gracefully (this is a good method for debugging)

75. c ++ container and generic algorithm separation. There are also function objects.
Considering the find algorithm, we need to solve three problems:
A. Some method is required for traversal; iterator
B. The elements need to be compared. Two versions are used. One is to use the = operator at the underlying layer of the element, and the other is to use the function pointer for user customization.
C. A public type is required to indicate the position of the element in the container;

76. generic algorithms accept common pointers or ieterator. A lot of things!

77. explicit, used with the constructor.
Explicit constructor indicates that constructors can only be displayed and used to prevent unnecessary implicit conversion.
For example:
Class {
Public:
A (INT ){};
}; Int test (const &){}
Test (2); // correct
If the constructor is declared as explicit, it will fail.

78. Wild pointer, which is a pointer to junk memory !! It is not a null pointer. For example, if you define a temporary object in the stack class and pass the object address out of the domain, the pointer becomes a wild pointer when the function exits.

79. function object. Good stuff. No data member, only member functions. So you do not need to instantiate it. Mostly used in generic algorithms ~~
Not only that, but it can also be seen as a "universal operator ".

80. pre-defined function objects: # include <functional>
Arithmetic, relational, logic

81. I have just seen Bjarne stroustrup (father of C ++)'s argument that we should use as few macros as possible. "If we see macros, it indicates that the program language, program code, or the programmer has problems ".
Replace the original macro with const, Enum, inline, and template. I personally agree!
However, macros are still the only solution for several important tasks, such as # include protection character (Guard), # ifdef and # If defined in Conditional compilation, and assert implementation.

81. When do not use generic algorithms. Re-sorting generic algorithms cannot be applied to associated containers. To increase the speed, the associated container has a structure that cannot be messy. Second, in view of the continuity of list storage, many algorithms

List is implemented in the form of member functions, so generic algorithms should not be used.

82. When does Allocator need to be used? The default C ++ alloctor is new and delete. New is not very efficient in allocating small memory and memory utilization. To improve performance, you need to define Allocator, for example

Map <int, int>, and then use the malloc and free functions of C in the Custom allocator.

83. Our design principle: programmers cannot display and manage many things. In particular, for a cooperative project, Division of modules, architecture of classes, interface definition, and other issues are all critical. What is a programmer should not display

Management of too many things? The essence is encapsulation, and it is a clever encapsulation. Make the entire program structure more "intelligent ". Make full use of the C ++ features supported by the C ++ compiler to make programs easier to expand and modules easier to use.
For example, the typical feature of object-oriented programming is that it transfers the burden of Type parsing from the programmer to the compiler.

84. Emphasize the polymorphism and dynamic binding again. For the first time, I felt the power of polymorphism. It was when I looked at the BCM code. Later I had a deep understanding when I analyzed the MFC! Later, when I was working on a project, I applied the polymorphism technology so that I could write

The upper-Layer Code of is highly scalable (class plug-ins with functions are implemented )!
The benefit of inheritance hierarchies is that we can program abstract basic classes, rather than individual types that constitute the inheritance hierarchy (simplified programming also facilitates expansion and upgrade ).
The so-called C ++ polymorphism mainly refers to the ability of the base class pointer to point to any derived class. (Therefore, polymorphism is inseparable from pointers and references ~~)
"Polymorphism" managed by programmers is not polymorphism. C ++ compiler is the most complex compiler, so don't waste it!

85. Before deriving a class, you must define the base class in the Declaration. The optical declaration is not acceptable (because the class is not defined internally and the compiler does not know its size, which is the same as the class member in this class ).

86. One of the main forms of object-oriented design is to abstract the definition of the base class and its public derivation. Note: there is still a gap between object-based and object-oriented.
Many beginners (who have no practical development experience) think that using classes is object-oriented. A big mistake!
When learning software engineering, we talk about the characteristics of object-oriented: encapsulation, inheritance, polymorphism, and messaging. That's right, four are indispensable. Encapsulation is the most basic (object-oriented) that many beginners understand ). The following three features are not practical.

Development experience.

87. When the base class is declared as a virtual function, its sub-classes do not need to be declared as virtual functions. Naturally, their children inherit the virtual features!

88. independence between the base class and the sub-class name domain: int I is defined in the base class Ca and int I is defined in the CA sub-class A1. There is no conflict between the two. They are all limited to their own class domains ~~
The same is true for the same member function name. Do not count on the member functions of the base class and the derived class to form an overloaded function set. Heavy Load
In this way, we can call the function of the base class: cache; ca1.ca: func ();

89. If there is a base class CA that derives from CA, both of them define a function void test () {} (not a virtual function ). Then:
Ca * PCA = new CA1 (); PCA-> test ();
In this case, PCA calls the test function of CA. How can this be understood?
Let's take a look at how the compiler works: First, new CA1 () indicates that the cache object is generated in the memory (The VFT only points to the cache object), and then Ca * PCA =, the compiler determines that PCA is a pointer to the CA class, and it will forget that this is actually

Cache class pointer, so you call PCA-> test (); the compiler will convert it to CA: Test (Ca * PCA); and what if you call a virtual function? Go back and check the first element of the object to which PCA points (the pointer to the virtual function table ).

This pointer is used to check the called function. It is naturally found in the class 'ca1.
So C ++'s inventor is very smart ~~

90. About. Operation compliance .. The operator is to let the compiler pass the address of an object before. To a function (if a function is followed) as a pointer ).

91. Refer to 88. How can we make the member functions of the base class and the member functions of the subclass form an overloaded set? The best way is to use the using statement, for example:
Class ca {void test (int I );}
Class A1: public CA {using CA: Test; void test (string S );}
The function declared by using cannot contain parameters. Therefore, using adds the overload set of the base class to the subclass ~~

92. When a base class object defines a protected member variable. If the base class object is referenced in a member function of a derived object of this class object, the derived object cannot operate on this member variable. However, if the input is

If you reference an object, you can copy the constructor)

93. youyuan, youyuan, and youyuan. Very useful. The key to establishing ambiguous relationships.

94. Calling sequence of constructor:
Base Class constructor. If there are multiple base classes, they appear in the order in the derived table, not in the order in which the members initialize the table.
If there are Member class objects, they are constructed in the order they are declared.
Then it is the construction of the derived class Object (that is, the execution body of the constructor ).
This is related to the memory sequence of data in the object body. It is constructed from a small memory size, which is in line with our habits. It can be considered that the base class sub-object is a special data member of the derived class object.

95. as a general rule, you should not directly assign values to members of a base class object in the constructor of the derived class, instead, the value should be passed to the constructor of the base class Object (in the initialization parameter list ). This is a good habit. Otherwise, the base class

It is tightly coupled with subclass, which is not conducive to code modification and maintenance.

96. Excessive permission of the virtual function. For example, if there is a derived class 'ca1' and 'ca1', what should I do if I want to call the virtual function of its base class ca? It's easy to do. Just add the Domain Restriction CA.

97. A member function declared as pure virtual can be defined. Is its definition meaningful. Yes. It can be called in the static mode of classname: In its subclass (to some extent, the virtual mechanism is restrained ).
The purpose of declaring it as a pure virtual function is to make the class become an abstract class and cannot be instantiated.

98. If polymorphism is involved, do not forget to declare the Destructor as a virtual function (hey, otherwise you will die badly ~~)
The structure order is the opposite to the structure order. A small program can be used to print strings (or trace debugging.
The compiler automatically adds the destructor of the base class and member to the destructor of the derived class. In fact, if you do not write a destructor, the default destructor process will be performed. For more information about the compiler, see ~~
I understand how to write a topic clearly ~~)

99. The upper-layer C ++ concept must be recognized at the Assembly level so that you can understand what the compiler has done and why C ++ can be designed like this. You do not need to remember many syntax details because you understand the internal mechanism.

100. The disassembly result indicates (vc6.0 ). Vftable is not used when an object calls a virtual function. The so-called dynamic binding is used only when the object pointer calls a virtual function.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.