Constructor doesn't set member variable

c++, class, constructor

Solution

In the following constructor, the line with `Foo()` does not delegate to the previous constructor. Instead, it creates a new temporary object of type `Foo`, unrelated to `*this`.

Foo(int b)
{
    bar = 0;
    Foo(); // NOTE: new temporary instead of delegation
    bar += b;
    cout << "Foo(int) called" << endl;
}

Constructor delegation works as follows:

Foo(int b)
    : Foo()
{
    bar += b;
    cout << "Foo(int) called" << endl;
}

However, this is only possible with C++11.

Problem

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?

Original source

Related problems