Kiran's Blog

Ramblings from a dehydrated mind…

  • Archives

    • 14,897

Initializing class members..

Posted by kiraninbng on June 28, 2006


Is there any difference between

CTest::CTest()
{
      m_csText = _T(“”); // Assigning Empty string to m_csText CString variable  
}

AND

CTest::CTest()
:m_csText(_T(“”))
{
}

The Answer is yes.The second example is sometimes the only way of initializing variables,used for const and reference variables.Apart from that in case of the first, before executing the code in the body of the constructor,all the variables needs to be initalized.Basically there is one intialization call by default and an assignment call in the body.The second case achieves the same with one initalization call.So it is a good practice to use intialization list whenever possible.

Advertisements

One Response to “Initializing class members..”

  1. Farpointer said

    Like u cant initialize a non-static const member anywere in the constructor other than the initializer list.

    CString &m_szrefStr; // in the header

    This can be only initialized in the initializer list of the constructor .

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: