The constructor does not set a member variable

My code is:

#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; } 

Exit:

 Foo() called Foo(int) called foo.bar is 5 

Why not the value of foo.bar 6? Foo() is called, but does not set bar to 1. Why?

+7
source share
4 answers

In the following constructor, the string with Foo() does not delegate to the previous constructor. Instead, it creates a new temporary object of type Foo that is not associated with *this .

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

The division of the constructor works as follows:

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

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

+12
source

you cannot use a constructor like regular functions. in your code call, Foo () creates a new object on the stack.

+3
source

Since you have this line in the constructor:

 bar = 0; 

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

+2
source

You must not call a constructor from another constructor

Cm

Is it possible to call a constructor from another constructor (make a constructor chain) in C ++?

If you are not using C ++ 11

+2
source

All Articles