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 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.
you can't use constructor like ordinary functions. in your code calling Foo() creates a new object in the stack.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With