This code is calling another ctor in one ctor:
#include <iostream>
using namespace std;
class F {
public:
F() { cout << "ctor1\n"; }
F(int) { cout << "ctor2\n"; }
~F() { cout << "dtor\n"; }
};
class Foo {
F f;
public:
Foo() : f() { cout << "1\n"; }
Foo(int i) : f(i) { Foo(); cout << "2\n"; }
};
int main() {
Foo object(1);
return 0;
}
The result is:
ctor2
ctor1
1
dtor
2
dtor
It seems the member variable f
destroyed twice here, is it Okay?
Here
Foo(int i) { Foo(); cout << "2\n"; }
You are not using delegating constructor. What you're doing is creating a temporary instance of Foo
in the constructor body (and destroying it immediately).
The correct syntax for delegating constructor is
Foo(int i) : Foo() { cout << "2\n"; }
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