Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy Constructor

I am new to C++ programming, I got a doubt when I was reading a C++ regarding copy constructor. Why copy constructor will call when we pass object of class to a outside function as pass by value. Please go through my code as below.

#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;

class Line
{
    public:
      int getLength( void );
      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;
    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)//here function receiving object as pass by value 
{
  cout << "Length of line : " << obj.getLength() <<endl;
}

// Main function for the program
int main( )
{
    Line line(10);
    display(line);//here i am calling outside function
   _getch();
   return 0;
}

In the above the I am passing object of class as parameter and display function receiving it as pass by value. My doubt is when I pass object to a function which is not a member of class why copy constructor is calling. if I receive object as reference in display() function[i.e display(Line &Obj)] it is not calling the copy constructor. Please help me what is the difference.

like image 442
nagaradderKantesh Avatar asked Mar 28 '26 11:03

nagaradderKantesh


1 Answers

When you pass something by value, the copy constructor is used to initialize the parameter that's passed -- i.e., what's passed is a copy of whatever you give, so of course the copy constructor is used to create that copy.

If you don't want the value copied, pass by (probably const) reference instead.

like image 166
Jerry Coffin Avatar answered Mar 30 '26 01:03

Jerry Coffin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!