I am passing a value to copy constructor as a reference, but an infinite loop is being invoked.
Here’s my class:
class Vector2f{
private:
GLfloat x;
GLfloat y;
public:
Vector2f();
Vector2f(const GLfloat _x, const GLfloat _y);
Vector2f(const Vector2f &_vector);
~Vector2f();
};
Here’s implementation of methods:
Vector2f::Vector2f():
x( 0.0f ),
y( 0.0f )
{
DebugLog("Vector2f constructor");
}
Vector2f::Vector2f(const GLfloat _x, const GLfloat _y):
x( _x ),
y( _y )
{
DebugLog("Vector2f constructor(%f, %f)", _x, _y);
}
Vector2f::Vector2f(const Vector2f &_vector):
x( _vector.getX() ),
y( _vector.getY() )
{
DebugLog("Vector2f copy constructor");
}
Vector2f::~Vector2f()
{
}
Here’s how I access the class:
Vector2f tempVector1 = Vector2f(0.0f, 0.0f);
DebugLog("tempVector1 initialized");
Vector2f tempVector2;
tempVector2 = Vector2f(0.0f, 0.0f);
DebugLog("tempVector2 initialized");
The results I get are:
Vector2f constructor(0.000000, 0.000000)
tempVector1 initialized
Vector2f constructor
Vector2f constructor(0.000000, 0.000000)
Vector2f copy constructor
Vector2f copy constructor
Vector2f copy constructor
...
Infinite loop occurs when trying to initialize previously created object.
If I try to copy tempVector1 into tempVector 2 an infinite loop occurs as well:
Vector2f tempVector2;
tempVector2 = Vector2f(tempVector1);
Why does it happen and how can I prevent it from getting into an infinite loop?
Thank you in advance.
I think the problem is in your assignment operator.
How does operator= look like?
It seems that operator= is calling him self in some way. Is it possible that the code snippet is taken from the body of operator= itself?
If it is then the solution is to change the code (inside operator=) such that it uses the copy ctor. The canonical form is as follows:
(See Exceptional C++ by Herb Sutter for more details)