Objects can be passed as regular variables (or references or pointers) to functions, but some care must taken be taken. When an object is passed as a parameter, an exact copy of the object is made without invoking the object s constructor. On the other hand, the object s destructor is called for that copy when it is no longer needed. Some objects ( especially ones where memory is allocated) will not work properly under these conditions.
In order to eliminate this problem, a class must implement a copy constructor , a special constructor that takes as an argument a const reference to that same type. For example:
class Mobject
{
public:
MObject(); // Regular constructor
Mobject( const Mobject &Original );// Note Original is not a required
name.
}
The copy constructor (instead of the default constructor) is called when an object is passed to a function, for autoinitialization, or when an object is returned from a function. It is not called during a normal assignment (you may write an overloaded operator to handle this). For example:
Foo( SomeObject ); // Copy constructor called to make a
copy of SomeObject
MObject A = B; // Copy ctor called for auto-initialization
B is an
MObject )
A = B; // Copy constructor is NOT called.