what is the purpose or when are we actually going to need a copy constructor? i know that a copy constructor is used when you want to copy an entire object. but when would you actually need to do this? wouldnt a normal constructor be enough?
what is the purpose or when are we actually going to need a copy constructor? i know that a copy constructor is used when you want to copy an entire object. but when would you actually need to do this? wouldnt a normal constructor be enough?
it's useful ie.
to send object clone to operation which can destroy it's orginal contents / state on error
so you don't lose orginal object.... or something....
I don't know if I'm right but it can be used like this:
Code:myClass X ; // some code here myClass Y = X ; // same as myClass Y( X ) ;
you define a copy constructor when you have pointers in your class...the default copy constructor c++ will give you will copy the address of the of whatever is being pointed and not the value...so all the changes to the new object will affect the old (they will become aliases)
i think a copy constructer is called in three circumstances (implicitly)...one i think is when you return an object
There is not the slightest indication that [nuclear energy] will ever be obtainable. It would mean that the atom would have to be shattered at will.
-Albert Einstein, 1932
I was working on an exercise last night that used a copy constructor. Here is the copy constructor
I was thinking why do we need the copy constructor, like yourself. As part of the exercise I had to overload the addition operator +. As the two operands had to remain unchanged then I had to use a temporary object to store the left hand operator. The copy constructor came in to play as you will see...Code:// Copy constructor String::String( const String © ) : length( copy.length ) { setString( copy.sPtr ); // call utility function }
An example of use of a copy constructor..Code:// Overload + operator; concatenates right operand to this object // without modifying the arguments String String::operator+( const String &right) const { String temp(*this); // copies left String to temp temp += right; // concatenates right String to temp return String(temp); // returns copy of temp }
Last edited by bigtamscot; 08-20-2004 at 01:49 PM.
hoping to be certified (programming in c)
here's the news - I'm officially certified.