13. Why does the overloaded assignment operator need to check for assignment to
ID: 665797 • Letter: 1
Question
13. Why does the overloaded assignment operator need to check for assignment to self (especially in a class that holds pointers to dynamic resources)? -------------------------------------------------------------------- 14. Explain the three main concepts represented in the Standard Template Library (STL), what their purpose is, and how they work together. -------------------------------------------------------------------- 15. (a) What are the advantages of using an stl::string to hold character data vs. a dynamic char array?
Explanation / Answer
13. Suppose we have an Array object say obj1 & if the program contains a statement like obj1 = obj1 somewhere, then the result of program is unpredictable as because the no self assignment check. To stop the above case from arising, we must add self assignment check while overloading the assignment operator. Below is an example for Self Assignment Check.
Example :
Array& Array::operator = (const Array &var1)
{
/* Checking self assignment*/
if(this != &var1)
{
// Deallocating the memory which is old
delete [] varPtr;
// allocating the new memory space
varPtr = new int [var1.size];
// copying the values
size = var1.size;
for(int i = 0; i < size; i++)
varPtr[i] = var1.varPtr[i];
}
return *this;
}
14. Three main concepts of STL :
· Container: (Arrays, Set, LinkedList, ArrayList, Dictionary and so on. Any of the data structure which is capable of storing collection of object can be termed as container in C++).
· Algorithm: (Algorithms are the functions designed for processing the sequences of elements.) There are several function built on algorithms like searching, sorting etc.
· Iterator: These are used to read data from collections or containers.
15. Advantages:
1. std::string has its own memory management mechanism so we can easily copy create and destroy them.
2. We cannot use our own buffer as std::string.
3. We will have to pass a c string or buffer to something which is expecting to take ownership of buffer – like some 3rd party C library.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.