Reputation: 309
/*The following program seems to mysteriously enter recursion even though there is none in sight. Compiler: g++ (Ubuntu 4.4.3-4ubuntu5.1) 4.4.3 Machine: x86 OS: Ubuntu 10.04 64-bit
*/
#include<iostream>
using namespace std;
class Test
{
public:
Test ():x(9)
{
cout << " Test::Test\n";
Test (x);
}
Test (int a)
{
cout << " Test::para\n";
}
private:
int x;
};
int main(void)
{
Test a;
return 0;
}
Why is this?
Upvotes: 2
Views: 205
Reputation: 545963
You cannot call other constructors like that in C++. But starting with C++11, you can forward constructor calls in the initialiser list:
class Test {
public:
Test (): Test(9) {
cout << " Test::Test\n";
}
Test (int a) : x(a) {
cout << " Test::para\n";
}
private:
int x;
};
See Wolfgang’s answer for an explanation of why your code crashes.
Upvotes: 2
Reputation: 4953
Test (x);
is parsed as
Test x;
... not as a constructor call. You can also write
Test (y);
and get the same behaviour.
Upvotes: 9