Click here to Skip to main content
15,892,005 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi EveryBody,

Can anyone can explain , while creating the copy constructor , why we are passing & ,why not value any one can explain about this?


Example:

C++
#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;
}


Regards,
Ranjith
Posted
Updated 18-Oct-13 1:58am
v4
Comments
Timberbird 18-Oct-13 8:17am    
One more questions on C++/OOP basics. I hope you're not using this site to get your homevork/exercise done
ranjithkumar81 28-Oct-13 8:28am    
NoI have a query on that, that's why i asked

 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 18-Oct-13 11:15am    
Right, a 5.
I actually wrote my own words to provide the rationale behind it, but later added a credit to your solution in my answer.
—SA
The rationale behind this design is quite apparent: the functionality is typically used for the cases when you need to create a clone of another object, which is typically complex enough. And '&' means pass-by-reference. Why pass by value and waste performance on copying everything memberwise on stack (this is this what pass-by-value would do, without '&') when a developer will clone it anyway? Would be wasteful and pointless.

Moreover, it is important to use const for the source object, to prevent accidental modification of it. Please see the page referenced in Solution 1.

See also: http://en.wikipedia.org/wiki/Clone_%28computing%29[^].

—SA
 
Share this answer
 
v3
Comments
nv3 18-Oct-13 11:34am    
Well explained, Sergey. By the way, it would not just be a waste of performance to pass the object by value, but a recursive call to the copy-constructor itself. So one simply can't define the copy constructor with pass-by-value ;-)
Sergey Alexandrovich Kryukov 18-Oct-13 11:51am    
Good point, thank you very much.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900