Jack
Jack

Reputation: 5870

why Copy Constructor was executed here

I could not understand why the copy constructor was executed when I just simply create one Object and execute one function.

using namespace std;

class Line {
   public:
      int getLength( void );
      Line( int len );             // simple constructor
      Line(const Line &obj);
      ~Line();                     // destructor
   private:
      int *ptr;
};

Line::Line(int len) {
   cout << "Normal constructor allocating ptr" << endl;
   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(void) {
   cout << "Freeing memory!" << endl;
   delete ptr;
}

int Line::getLength( void ) {
   return *ptr;
}

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

int main() {
   Line obj(10);
   display(obj);
   return 0;
}

Upvotes: 0

Views: 83

Answers (3)

Waqar
Waqar

Reputation: 9331

You are creating a copy here:

void display(Line obj)

This results in a call to copy constructor. If you want to avoid this, simply pass by reference:

void display(const Line& obj)

Upvotes: 2

cigien
cigien

Reputation: 60208

This function:

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

takes the Line parameter by value, which calls the copy constructor when you invoke display here:

Line obj(10);
display(obj);

If you don't want to copy the argument then pass it by reference:

void display(Line &obj) {

or by const reference if it's not going to be modified:

void display(Line const &obj) {

Note that passing by const reference requires changing the signature of getLength to be const-qualified:

int getLength( void ) const;

Upvotes: 3

Dave
Dave

Reputation: 4291

When you pass the Line object to display, it is passed by value, meaning it gets copied.

Upvotes: 2

Related Questions