General discussion

Locked

a simple question on c++

By monukaushal ·
can somebody can clear the use of copy constructor in c++. and if possible give a small and suitable example regarding the copy constructor.

This conversation is currently closed to new comments.

2 total posts (Page 1 of 1)  
| Thread display: Collapse - | Expand +

All Comments

Collapse -

by tehilinski In reply to a simple question on c++

A copy constructor is used to create an instance from another instance, e.g.:
MyClass A;
MyClass B (A);

When B is instantiated, the following constructor is called:
B (B const & object);

Use the body of the copy constructor to copy member data from the source object. e.g.:

class Ints
{
int x, y;
Ints (Ints const & object)
{
x = object.x;
y = object.y;
}
};

Collapse -

Copy Constructor

by eziogava@angloirishbank. In reply to a simple question on c++

The copy constructor implements the construction of an instance when another one is given. If you implement the copy constructor you should also implement the equal operator with the same semantic. The copy constructor is used in all the situations where a copy of an instance is needed, for instance when passing parameters by value to a function or when returning an object from a function. Cloning an object may or may not be done by using the same semantic of the copy constructor. This depends if you require a shallow copy or a deep copy in the Clone() method. Cloning is best implemented by realizing a proper interface.

Best Regards
eziogava@angloirishbank.ie

Back to Web Development Forum
2 total posts (Page 1 of 1)  

Related Discussions

Related Forums