The copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously. The copy constructor is used to:Initialize one object from another of the same type.
- Copy an object to pass it as an argument to a function.
- Copy an object to return it from a function.
- Don't write a copy constructor if shallow copies are ok
- If the object has no pointers to dynamically allocated memory, a shallow copy is probably sufficient. Therefore the default copy constructor, default assignment operator, and default destructor are ok and you don't need to write your own.
If you need a copy constructor, you also need a destructor and
operator=
If you need a copy constructor, it's because you need something like a deep copy, or some other management of resources. Thus is is almost certain that you will need a destructor and override the assignment operator.Copy constructor syntax
The copy constructor takes a reference to aconst
parameter. It isconst
to guarantee that the copy constructor doesn't change it, and it is a reference because a value parameter would require making a copy, which would invoke the copy constructor, which would make a copy of its parameter, which would invoke the copy constructor, which ...Here is an example of a copy constructor for the Point class, which doesn't really need one because the default copy constructor's action of copying fields would work fine, but it shows how it works.//=== file Point.h ============================================= class Point { public: . . . Point(const Point& p); // copy constructor . . . //=== file Point.cpp ========================================== . . . Point::Point(const Point& p) { x = p.x; y = p.y; } . . . //=== file my_program.cpp ==================================== . . . Point p; // calls default constructor Point s = p; // calls copy constructor. p = s; // assignment, not copy constructor.
Difference between copy constructor and assignment
A copy constructor is used to initialize a newly declared variable from an existing variable. This makes a deep copy like assignment, but it is somewhat simpler:- There is no need to test to see if it is being initialized from itself.
- There is no need to clean up (eg, delete) an existing value (there is none).
- A reference to itself is not returned.
x=p.x;
ReplyDeletey=p.y;
how they are working?
These statements only assigned the object's p members p.x and p.y to x and y
DeleteThis comment has been removed by the author.
ReplyDelete