O
Ook
Given the following code, when I do Zoot v3 = v1, it does not execute the
operator= function, instead it executes my copy constructor. Why is this,
and how do I get it to execute my overloaded operator= function instead?
Everything looks all right, it compiles, it runs as expected except for the
v3 = v1. I expected it to call Zoot:perator=, but when I trace through it,
it calls the copy contstructor instead.
Class Zoot {
public:
// Constructors
Zoot(int size = 0) : _size(size), _data(_size ? new int[_size] : 0) { }
Zoot(const Zoot& vec);
// Overload operator=
Zoot& operator=(const Zoot& rhs);
private:
int _size;
int* _data;
}
...........
int main()
{
Zoot v1(5);
Zoot v2( v1 );
Zoot v3 = v1;
return 0;
}
// Copy constructor
Zoot::Zoot(const Zoot& vec)
{
// Make the new _size twice as big as the existing one
_size = vec._size * 2;
// Initialize _data
_data = new int[ _size ];
}
// Assignment operator overload
Zoot& Zoot:perator=(const Zoot& rhs)
{
if( this != &rhs )
{
delete [] _data;
_data = new int[_size];
}
return *this;
}
operator= function, instead it executes my copy constructor. Why is this,
and how do I get it to execute my overloaded operator= function instead?
Everything looks all right, it compiles, it runs as expected except for the
v3 = v1. I expected it to call Zoot:perator=, but when I trace through it,
it calls the copy contstructor instead.
Class Zoot {
public:
// Constructors
Zoot(int size = 0) : _size(size), _data(_size ? new int[_size] : 0) { }
Zoot(const Zoot& vec);
// Overload operator=
Zoot& operator=(const Zoot& rhs);
private:
int _size;
int* _data;
}
...........
int main()
{
Zoot v1(5);
Zoot v2( v1 );
Zoot v3 = v1;
return 0;
}
// Copy constructor
Zoot::Zoot(const Zoot& vec)
{
// Make the new _size twice as big as the existing one
_size = vec._size * 2;
// Initialize _data
_data = new int[ _size ];
}
// Assignment operator overload
Zoot& Zoot:perator=(const Zoot& rhs)
{
if( this != &rhs )
{
delete [] _data;
_data = new int[_size];
}
return *this;
}