Beginner questions about overloading + operator

This is from Ivor Horton's Beginning Visual C++ 2013:

It gives an example of overloading + operator for a simple class called box. The box basically only 3 data members which are the length, width and height of the box. The overloaded operator function is shown below:

1
2
3
4
5
6
7
8
// Function to add two CBox objects
CBox CBox::operator+(const CBox& aBox) const
{
	// New object has larger length and width, and sum of heights
	return CBox(std::max(m_Length, aBox.m_Length),
	std::max(m_Width , aBox.m_Width) ,
	m_Height + aBox.m_Height);
}


The book says:

The return process will make a temporary copy of the local CBox object you create, and the temporary copy is passed back to the calling function, not the local object. The local object is destroyed on return from the function.

I have the following questions:
(1) Do I understand correclt that the line return CBox creates a temporary object of which a copy is created and sent back, thus creating 2 temporary objects when we add 2 box objects? Why not create just 1 temporary copy and return it?
(2) Why don't we use the operator new to create a new CBox and send it back? Certainly if we use new we save copying twice by sending a pointer.
(3) If we use new will the destructor be called in this temporary object? Or is it that it is not temporary anymore since we have used the new operator to create it?
Last edited on
closed account (48T7M4Gy)
Keeping in mind your (valid) questions are related to the operations of the compiler, which the average programmer accepts to a large extent as a mystery, the short answer, or at least a start on it, is:
http://en.cppreference.com/w/cpp/language/overload_resolution
1) No. Copy elision (Return Value Optimization), creates a single instance.
http://en.cppreference.com/w/cpp/language/copy_elision

2) Using new would create a dynamic object that would later have to be deleted (creating the possibility of a memory leak). Returning by value is cleaner for small objects.

3) No, the destructor is not called if new is used. The caller of operator + would be responsible for deleting the object created. The destructor would be called when the object is eventually deleted. This would be a very unconventional overload of operator +.

Last edited on
Topic archived. No new replies allowed.