My code:
#include <iostream>
using namespace std;
class Foo
{
public:
int bar;
Foo()
{
bar = 1;
cout << "Foo() called" << endl;
}
Foo(int b)
{
bar = 0;
Foo();
bar += b;
cout << "Foo(int) called" << endl;
}
};
int main()
{
Foo foo(5);
cout << "foo.bar is " << foo.bar << endl;
}
The output:
Foo() called
Foo(int) called
foo.bar is 5
Why isn’t the foo.bar value 6? Foo() is called but doesn’t set bar to 1. Why?
In the following constructor, the line with
Foo()does not delegate to the previous constructor. Instead, it creates a new temporary object of typeFoo, unrelated to*this.Constructor delegation works as follows:
However, this is only possible with C++11.