C++ Copy Constructor
C++ Copy Constructor
C++ Copy Constructor
class Line {
public:
int getLength( void );
Line( int len ); // simple constructor
Line( const Line &obj); // copy constructor
~Line(); // destructor
private:
int *ptr;
};
Line::~Line(void) {
cout << "Freeing memory!" << endl;
delete ptr;
}
display(line);
return 0;
}
When the above code is compiled and executed, it produces the following result −
Normal constructor allocating ptr
Copy constructor allocating ptr.
Length of line : 10
Freeing memory!
Freeing memory!
Let us see the same example but with a small change to create another object using
existing object of the same type −
#include <iostream>
class Line {
public:
int getLength( void );
Line( int len ); // simple constructor
Line( const Line &obj); // copy constructor
~Line(); // destructor
private:
int *ptr;
};
Line::~Line(void) {
cout << "Freeing memory!" << endl;
delete ptr;
}
Line line1(10);
display(line1);
display(line2);
return 0;
}
When the above code is compiled and executed, it produces the following result −
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!