Constructor and destructor design in C++


constructor called done in 2 steps. 1. member initialization.
// this call constructor
2. call of constructor body.
// this call assignment operator
MyClass():member(),base(){
step1
x=val;
step2
}


1. use initialization list for members. if list long use init method. 2. define default constructor otherwise unable create array of object. 3. define virtual destructor if need to use base* to reference to derived object. 4. always define empty implementation for virtual destructor.virtual destructor work is that the most derived class's destructor is called first, then the destructor of each base class is called. 5. order of member initialization in order they declare in class. 6. virtual function increase object size by vptr, if your class doesn't need any virtual function then try to avoid virtual destructor. 7. ownership of pointer data members need to take care for all kind of constructor and assignment operator and destructor. 8. avoid object creation by default constructors.It's looks like using variable without initializing or 2 step initialization overhead, better to use constructor which take initialization input data. create a object using default constructor. assign or initialized data.


copy constructor
derived copy constructor should call base copy constrictor. do assignment for all data members. ownership of pointer data need to take care similar to constructor.

-----------STILL DRAFTING---------

No comments:

Post a Comment

would you like it. :)