7

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?

Guilherme Bernal
  • 8,183
  • 25
  • 43
  • 4
    `Foo();` creates an unnamed temporary object and immediately destroys it. What is it that you _expected_ to happen? – ildjarn May 25 '12 at 20:08

4 Answers4

12

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.

nosid
  • 48,932
  • 13
  • 112
  • 139
  • +1 for noting "only possible with C++11" --> http://meta.stackexchange.com/q/133642/186397. – Drise May 25 '12 at 20:11
3

you can't use constructor like ordinary functions. in your code calling Foo() creates a new object in the stack.

sithereal
  • 1,656
  • 9
  • 16
2

Because you have this line in the constructor:

bar = 0;

You are trying to call the other constructor with Foo() call in the second constructor, but it just creates a temp Foo instance.

Hakan Serce
  • 11,198
  • 3
  • 29
  • 48
2

You're not supposed to call a constructor from another constructor

See

Can I call a constructor from another constructor (do constructor chaining) in C++?

Unless you're running C++11

Community
  • 1
  • 1
A B
  • 4,068
  • 1
  • 20
  • 23