I have got the following c++ code. I can compile it with g++ 4.9.2 on Linux machine. Then when I run it, it prints 10. It seems that a new object is created and assigned to the pointer created using const_cast in the default constructor. There are no memory leaks (which I checked using valgrind). Is this some kind of an undefined behavior or is it legal?
#include <iostream>
using namespace std;
class A
{
public:
A() : x(0)
{
A *tmp = const_cast<A*>(this);
*tmp = A(10);
}
A(int x)
{
this->x = x;
}
int getX() const
{
return x;
}
private:
int x;
};
int main()
{
A a;
cout << a.getX() << endl;
return 0;
}
const_cast
has nothing to do with the behavior you experience. Your code may be simplified to the following:
A() : x(0)
{
*this = A(10);
}
So, here the following happens if we want to create an object using a default constructor:
this
is reserved.0
is assigned to the member x
of this
.A
is created using the constructor A(int)
. This new object member x
has value 10
.*this
. Thus, value of member x
of this
becames 10
.this
is returned.This is perfectly legal and expected behavior.