There are three program instances in which a class object is initialized with another object of its class.
1) an object's explicit initialization
class X {...};
X  x;
X xx = x;  //explicit initialization of one class object with  another
2) an object is passed as an argument to a function
3) when a function returns a class object.
This may result in the generation of a temporary class object or the actual transformation of program code (or both).
Default memberwise Initialization
What if the class does not provide an explicit copy  constructor?
default memberwise initialization copies the value of each  built-in or derived data member from the one class object to another. A member  class object, however, is not copied; rather, memberwise initialization is  recursively applied.
In practice, a good compiler can generate bitwise copies for most class objects since they have bitwise copy semantics.
The standard states that:
A class object can be copied in  two ways, by initialization and by assignment. Conceptually, these two operations are  implemented by a copy constructor and a copy assignment operator.
The standard distinguishes between a trival and nontrivial copy constructor. It is only the nontrivial instance that in practice is synthesized within the program. The criteria for determining whether a copy constructor is trivial is whether the class exhibits bitwise copy semantics. A default copy constructor need not be synthesized, if the declaration exhibits bitwise copy semantics, and the initialization need not result in a function call.
There are four instances when bitwise copy  senmantics NOT exhibited by a class:
1) When the  class contains a member object of a class for which a copy constructor exists  (either explicitly declared by the class designer or synthesized by the  complier).
2) When the class is derived from a base class for which a copy  constructor exists
3) When the class declares one or more virtual functions (we need to initialize vptr correctly)
4) When the class is derived from an inheritance chain in which  one or more base classes are virtual.
Resetting the Virtual Table Pointer: When we assign derived class object to base class object, we need to set vptr to base class virtual table. 
Handling the Virtual Base Class Subobject: The problem is not  when one object of a class is initialized with a second object of the same exact  class. It is when an object is initialized with an object of one of its derived  classes.
No comments:
Post a Comment