Reputation: 99
I am trying to implement delegated constructor without initialization. This is because I need the appropriate values obtained by a function call. How do I write a proper code without code repetition?
class foo
{
private:
// Something
public:
foo() = delete;
foo(double a, double b, double c)
{
// Something
}
foo(int n)
{
double a, b, c;
// a, b, c passed by reference and appropriate value is obtained here.
function_call(n, a, b, c);
// construct this object as if the call is foo(a, b, c) now
foo(a, b, c); // ??? Does this work?
}
};
Upvotes: 0
Views: 32
Reputation: 206617
foo(a, b, c); // ??? Does this work?
No, it does not work. It creates a temporary object and fails to initialize the member variables of the current object.
My suggestion:
Change function_call
to return a std::tuple<double, double, double>
instead of updating the values of objects passed by reference.
Then, you can use:
class foo
{
private:
foo(std::tuple<double, double, double> const& t) : foo(std::get<0>(t), std::get<1>(t), std::get<2>(t)) {}
public:
foo() = delete;
foo(double a, double b, double c)
{
// Something
}
foo(int n) : foo(function_call(n)) {}
};
You may also use std::array<double, 3>
as the return value of function_call
and update the constructor accordingly.
foo(std::array<double, 3> const& arr) : foo(arr[0], arr[1], arr[2]) {}
Upvotes: 1