Main BLOGGER
Google
WWW THIS BLOG
Monday, January 22, 2007
 
Using copy construction and assign operator
statement:
  Using initializer in copy constructor to avoid double initialization for class type members
Do not reuse the same for copy constructor and assign operator even they are doing the same thing!

In C++, assignment and copy construction are different because the copy constructor initializes uninitialized memory, whereas assignment starts with an existing initialized object.
If your class contains instances of other classes as data members, the copy constructor must first construct these data members before it calls operator=.
The result is that these members get initialized twice, as cctest shows. Got it? It's the same thing that happens with the default constructor when you initialize members using assignment instead of initializers.

For example:
CFoo::CFoo() 
{
m_obj = DEFAULT; // cause double initialization of m_obj, one for m_obj, another for "="
}
As opposed to:
CFoo::CFoo() : m_obj(DEFAULT)
{
}

--
Pop (Pu Liu)



<< Home

Powered by Blogger

Google
WWW THIS BLOG