Account oldAcct( "Anna Livia Plurabelle" ); and Account newAcct( oldAcct ); is referred to as default memberwise initialization. Default because it occurs automatically whether or not we supply an explicit constructor. Memberwise because the unit of initialization is the individual nonstatic data member rather than a bitwise copy of the entire class object.class Foo() {
public:
...
private:
char* m_name;
int m_index;
};
If there is no the declaration of copy constructor in the class, compiler will implicitly generate a default copy constrctor to perform memberwise initialization as follow:
inline Foo::
Foo( const Foo& rhs ){
m_name = rhs.m_name;
m_index = rhs.m_index;
}
Account newAcct( oldAcct );
extern bool cash_on_hand( Account acct );
if ( cash_on_hand( oldAcct ))
// ...
extern Account
consolidate_accts( const vector< Account >& )
{
Account final_acct;
// do the finances ...
return final_acct;
}
// five string copy constructors invoked
vector< string > svec( 5 );
(In this example, one temporary is created using the string default constructor and then this temporary is copied in turn into the five elements of the vector using the string copy constructor.)
svec.push_back( string( "pooh" ));
class Account {
std::string _name;
int _index;
};
How to write a copy stor? You may write something like:
class Account {
Account( const Account& rhs ){
_name = rhs._name;
_index = rhs._index;
}
std::string _name;
int _index;
};
However, there are two steps involved in the copy ctor: 1) Initialize _name by the default ctor of std::string. 2) Assign rhs._name to _name. The second step is redundant, a better solution is as follows:
class Account {
Account( const Account& rhs ) : _name(rhs._name) {
_index = rhs._index;
}
std::string _name;
int _index;
};