Suppose you are implementing an assignment operator, a copy constructor, and an
ID: 3671381 • Letter: S
Question
Suppose you are implementing an assignment operator, a copy constructor, and an operator +=. For which of these functions do you need to worry about possible "self-application" (where the argument is the same as the object that activates the function):
A. Only one of the three functions has possible self-application
B. The assignment operator and the copy construtor have possible self-application
C. The assignment operator and the operator += have possible self-application
D. The copy construtor and the operator += have possible self-application
E. All three functions have possible self-application
When a class uses dynamic memory, what member functions should be provided by the class?
A. The assignment operator.
B. The copy constructor.
C. A destructor.
D. All of the above.
Explanation / Answer
memory allocated at run time exact size can be variable.
dynamic memory doesn't have a name,so pointer used to link to this memory.
objects can be allocated dynamically. when an object is created the constructor runs.
deallocation with delete.
copy constructor
themethod which simply copies the content and This is because the default copy constructor provided by the compiler does a reference copy. It does not do a deep copy.
That is it will just copy the reference i.e the address. The default copy constructor will not allocate new memory for the pointers but will just assign the previous object's memory address.
However when we call a copy constructor we expect two objects that have different memory regions allocated. So we expect that the pointers of both the objects will point to different memory locations and hence change in one will not reflect in other.
That is why we need to write our own copy constructor in case we have pointer variables inside our class and have some dynamic memory locations allocated.
the assignment operator which cannot allocates the memory as the variable size already created at the time of initialization
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.