Constructor/Destructor/Copy Constructor/operator =

来源:互联网 发布:人力资源管理知乎 编辑:程序博客网 时间:2024/05/22 13:12

1) If you have created any constructors or even copy constructors, the compiler won't create default constructor for you.

2) operator =, copy constructor and destructor are siblings, if we overwrite any of them, we should overwrite the rest of them.

3) The order of construction/destruction of class objects. If a class contains a series of objects that belong to different classes, the order of constructions of these objects depends on the order that these objects are defined, not depends on the order in the initialization list of the constructor. The order of destructions of these objects is reversed. i.e. if object A is the first one to be constructed, then it is the last one to be destructed.

4) The order of construction/destruction of base classes. If a class derives from multiple classes, then the order of construction of base classes depends on the order which base class is derived first, not depends on the order in the initialization list. The order of destructions of base classes is reversed. e.g. class C : public A, public B {..}, then constructor of A is called first.

5) The order of construction/destruction between base classes and member objects. The construction of base classes is called first, then the construction of member objects is called. The destruction between base classed and member objects is reversed.

6) The difference between operator = and copy constructor. Copy constructor has no return value while operator = return a reference to a object. Operator = has to check if it is a self-assignment.such as if(this == &other). Operator = has to release resources that have acquired while copy constructor doesn't need to check since it is a kind of construction.

7) If a class contains other class objects, and you don't explicitly call its constructor in the initialized list, compiler will call  the default constructor for this object. If this object doesn't have a default constructor, compiler will complain.

class AAA{public:    AAA(){}// default constructor    AAA(int i):v(i){cout<<"constructor AAA"<<endl;}    ~AAA(){cout<<"destructor AAA"<<endl;}private:    int v;}; struct BBB{BBB(int i) {cout<<"constructor BBB"<<endl;}~BBB(){cout<<"destructor BBB"<<endl;}};struct Compound{BBB b;AAA a;//here we don't explicitly call the constructor of class AAA, //compiler will try to call the default constructor, if class //AAA doesn't have a default constructor, compiler will complain.       Compound(int i):b(i){}}int main(){    Compound c(1);    return 0;}


6)