Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copy constructor in c++ with different arguments

Why this code is calling the copy constructor when the object passed is not of type Line and there is no equal to operator/explicit calling. Is there a difference between Line A and Line A().
I read from many online tutorials that it should be of Line type.I am a newbie to C++.Please help

 #include <iostream>
    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;
    // 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(void)
{
    cout << "Freeing memory!" << endl;
    delete ptr;
}
int Line::getLength( void )
{
    return *ptr;
}

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

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

   display(line);

   return 0;
}
like image 833
Hemanshu Sethi Avatar asked Apr 28 '26 21:04

Hemanshu Sethi


1 Answers

It's because your display method accepts its argument by value - as a result a copy is made when you pass the argument. To avoid the copy, declare the parameter to be a reference to a Line instead, by adding an ampersand, &:

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

If you want to make sure that the display method doesn't modify your Line, also consider making it a const reference:

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

You'd then also need to declare your Line::getLength() method to be a const member function, since otherwise the compiler won't allow you to invoke it on a const object:

int getLength( void ) const;
like image 109
atkins Avatar answered Apr 30 '26 12:04

atkins



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!