was struggling these days.
The problem is the constructor calling.
I wrote a piece of code like:
#include <iostream>
using namespace std;
class Foo
{
private: int _n;
public:
Foo() { Foo(5);}
Foo(int n) {_n=n; cout << n << endl; }
};
int main()
{
Foo* foo = new Foo();
return 0;
}
When I constructed a Foo object outside using the default constructor:
Foo* f = new Foo();
I suppose variable _n is 5, however, it's NOT.
It's ok in Java but NOT in c++.
In addition, in Visual C++ 6 sp 6,
Foo() {this->Foo(5);}
works.
However, this expression is refused by gcc/g++ 4.
Finally, I found out the solution.
Simply changing the default constructor into
Foo() {Foo(5);}
into
Foo() { new (this) Foo(5); }
solves the problem.
What does "this" in parentheses do?