shiladitya basu shiladitya basu - 1 month ago 7
C++ Question

C++ copy constructor called multiple times

I was trying to understand the basics of copy constructors and came across the following example.

#include <iostream>

using namespace std;

class Line
{
public:
int getLength() const;
Line( int len ); // simple constructor
Line( const Line &obj); // copy constructor
~Line(); // destructor

private:
int *ptr;
};

// Member functions definitions including constructor
Line::Line(int len)
{
cout << "Normal constructor allocating ptr" << endl;
// allocate memory for the pointer;
ptr = new int;
*ptr = len;
}

Line::Line(const Line &obj)
{
cout << "Copy constructor allocating ptr." << endl;
ptr = new int;
*ptr = *obj.ptr; // copy the value
}

Line::~Line()
{
cout << "Freeing memory!" << endl;
delete ptr;
}
int Line::getLength() const
{
return *ptr;
}

void display(Line obj)
{
cout << "Length of line : " << obj.getLength() <<endl;
}

// Main function for the program
int main( )
{
Line line1(10);

Line line2 = line1; // This also calls copy constructor

//display(line1);
//display(line2);

return 0;
}


When executed, it gives the following output.

Normal constructor allocating ptr
Copy constructor allocating ptr.
Copy constructor allocating ptr.
Length of line : 10
Freeing memory!
Copy constructor allocating ptr.
Length of line : 10
Freeing memory!
Freeing memory!
Freeing memory!


The copy constructor is called only once, in the
Line line2 = line1;
But it seems that the copy constructor is being called twice. So I commented out the
display(line1);
and
display(line2);
. After that the output is something like this.

Normal constructor allocating ptr
Copy constructor allocating ptr.
Freeing memory!
Freeing memory!


So the problem(I don't know if I should call it a problem or its a default standard in C++) is with the display function. Could it be because the display() function automatically creates a copy of the object its processing and that's why the copy constructor is called twice for each instance? Kindly clarify. Thanks.

Answer

with void display(Line obj), you pass object by value, so create copy.

You should pass by (const) reference to avoid the copies:

void display(const Line& obj)
Comments