Monday, June 6, 2011

What class members require initializer list in definition of constructor

Member objects of classes without default constructors
Const members
Reference members

Assume that T2 in the following does not have default constructor
Class MyClass
{
       string name;
       const int i;
       T1&  obj1;
       T2 obj2;
       MyClass(){};           //wrong - i, T1, T2 require initialization in the initializer list
}

Adding  following constructor(and corresponding declaration in the class declaration) would fix the issue
MyClass::MyClass(const int _i, T1& _obj1, T2 _obj2):_i(i), obj1(_obj1), obj2(_obj2){}

Ref. C++ Language, The (3rd Edition) by Bjarne Stroustrup , page 248.

Friday, June 3, 2011

Automatic destruction of dynamic object

Use unique_ptr<> template object for that.
Ex
{
       unique_ptr<T> p = new T();
}
Dynamic object that is referred by p is destroyed when control thread exits the block.
This is achieved by coupling automatic variable p with the dynamic object. It is ensured by unique_ptr 

Excellent  article on www.stackoverflow.com by Matthieu M.