Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor doesn't set member variable

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?

like image 953
Guilherme Bernal Avatar asked May 25 '12 20:05

Guilherme Bernal


2 Answers

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.

like image 200
nosid Avatar answered Nov 06 '22 05:11

nosid


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

like image 3
sithereal Avatar answered Nov 06 '22 05:11

sithereal