This one does not use the assignment operator (the two lines are equivalent, as far as I know). =
is used in the syntax but operator=
is not actually used:
myClass myVariable = myClass(123);
//or
myClass myVariable(123);
This one uses the assignment operator:
myClass myVariable;
myVariable = myClass(123);
If assignment operator is badly or not implemented, first statement works, second may (and will most likely) crash.
#include <iostream>
#include <string.h>
using namespace std;
class Dvector
{
public:
Dvector( int thesize = 0 )
{
std::cout << "Constructing object of size " << thesize << std::endl;
size = thesize;
data = new double[size];
}
Dvector( const Dvector& v )
{
std::cout << "Constructing object of size " << v.size << " by copy" << std::endl;
size = v.size;
data = new double[size];
memcpy( data, v.data, sizeof(double)*size );
}
Dvector& operator=( const Dvector& v )
{
std::cout << "Assigning object of size " << v.size << std::endl;
if ( &v != this )
{
size = v.size;
data = new double[size];
memcpy( data, v.data, sizeof(double)*size );
}
return *this;
}
~Dvector()
{
std::cout << "Destroying object" << std::endl;
delete [] data;
}
private:
double* data;
int size;
};
int main() {
Dvector v = Dvector(3);
return 0;
}
Displays:
Constructing object of size 3
Destroying object
When:
int main() {
Dvector v;
v = Dvector(3);
return 0;
}
Displays:
Constructing object of size 0
Constructing object of size 3
Assigning object of size 3
Destroying object
Destroying object
And would have crashed if copy constructor was not defined...because then v.data
ends up pointing to data
allocated by temporary variables (Dvector(3)
) and then deleted. Possible crash when trying to access v.data
or upon v
destruction (deleting already freed memory).