首页 > 代码库 > Class

Class

1. No const constructor

Unlike other member functions, constructors may not be declared as const . When we create a const object of a class type, the object does not assume its “constness” until after the constructor completes the object’s initialization. Thus, constructors can write to const objects during their construction


2. Synthesized default constructor

The compiler-generated compiler is known as synthesized default constructor

For most classes, the synthesized default constructor initializes each data member as follows: if there is an in-class initializer, use it to initialize the member; otherwise, default initialize the member.

3.Why sometimes should difine default constructor for classes?

A reason to define default constructor is that for some classes, the synthesized default constructor does the wrong thing. The objects of built-in or compound type(such as array and pointer) that are defined inside a block have undefined value when they are default initialized. Therefore, classes that have members of built-in or compound type should either be initialized inside the class or define their own version of default constructor.

Another reason that some classes must define their own default constructor is that sometimes the compiler is unable to synthesize one. For example, if a class has a member of a class type, and that class doesn‘t have a default constructor , then the compiler can‘t initializer that member.

P.S. Classes that have members of built-in or compound type rely on synthesized default constructor only if all such members have in-class initializer.

4. Constructor initializer list

Constructor initializer list specifies initial values for one or more data members of the object being created.

5. Difference of default access level between class and struct

The default access specifier in strcut is public whereas that in class is private. 

P.S. The only difference using class and using strcut to define a class is the default access level.

 6. friend class or function

A class can allow other class or function to access its non-public members by making the class or function a friend. 

P.S. Friend declaration should be inside a class definition and they may be anywhere in the class. Friends are not members of the class and aren‘t affected by the access specifier. 

7. Benefits of encapsulation

1) User code can‘t inadvertently corrupt the state of an encapsyulated object

2) The user-level code doesn‘t need change when the implementation of can encapsulated class changes.

8. Friend class

The member functions of a friend class can access all the members, including non-public members of the class granting friendship. 

P.S. Classes and non-member functions need not have been declared before they are used in a friend declaration.

9. Class scope

 

Class