I am learning the constructor and destructor, and have learned the rule of three.
I am now playing a small example from tutorialspoint. I notice the example doesn't have an assignment operator, but the code somehow works well.
e.g., as to Line a(b)
, when I change the content in a, e.g., *(a.ptr), *(b.ptr) is not changed.
I also write one assignment operator (commented), the code also works.
Now I am confused. It seems on some occasions, only copy constructor is enough. Could anyone comment on this to help me know better the mechanism of memory allocation involved in calling copy constructor?
Thanks!
#include <iostream>
using namespace std;
class Line
{
public:
int getLength( void );
Line( int len ); // simple constructor
Line( const Line &obj); // copy constructor
~Line(); // destructor
void doubleLength(void);
Line &operator=(const Line &);
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; //simply allocates memory for one integer, and returns a pointer to it.
*ptr = len;
}
Line::Line(const Line &obj)
{
cout << "Copy constructor allocating ptr." << endl;
ptr = new int;
*ptr = *obj.ptr; // copy the value
}
// // copy assignment operator, added by me
// Line& Line::operator=(const Line& that)
// {
// if (this != &that)
// {
// delete ptr;
// // This is a dangerous point in the flow of execution!
// // We have temporarily invalidated the class invariants,
// // and the next statement might throw an exception,
// // leaving the object in an invalid state :(
// this->ptr = new int;
// this->ptr = that.ptr;
// }
// return *this;
// }
Line::~Line(void)
{
cout << "Freeing memory " << ptr << endl;
delete ptr;
}
int Line::getLength( void )
{
return *ptr;
}
void Line::doubleLength(void)
{
*ptr = *ptr * 2;
}
void display(Line obj)
{
cout << "Length of line : " << obj.getLength() <<endl;
}
// Main function for the program
int main( )
{
Line line1(10);
// Line line2 = line1; // This also calls copy constructor
Line line2(line1); // performed by copy assignment operator
line2.doubleLength();
display(line1);
display(line2);
return 0;
}
I get the output:
Normal constructor allocating ptr
Copy constructor allocating ptr.
Copy constructor allocating ptr.
Length of line : 10
Freeing memory 0x836c028
Copy constructor allocating ptr.
Length of line : 20
Freeing memory 0x836c028
Freeing memory 0x836c018
Freeing memory 0x836c008