12.8 Overlapping and delegating constructors


https://www.learncpp.com/cpp-tutorial/overlapping-and-delegating-constructors/
コンストラクション関数でオーバーラップ機能を実現するにはどうすればいいですか?

The obvious solution doesn’t work

class Foo
{
public:
    Foo()
    {
        // code to do A
    }

    Foo(int value)
    {
        Foo(); // use the above constructor to do A (doesn't work)
        // code to do B
    }
};
上記のやり方は実行可能に見えるが,実行できない.

Delegating constructors

class Foo
{
private:

public:
    Foo()
    {
        // code to do A
    }

    Foo(int value): Foo{} // use Foo() default constructor to do A
    {
        // code to do B
    }

};
メンバーinitリストから呼び出すことは可能です
これを委任構造関数(委任)と呼ぶ
これは別の例です
#include <string>
#include <iostream>

class Employee
{
private:
    int m_id{};
    std::string m_name{};

public:
    Employee(int id=0, const std::string &name=""):
        m_id{ id }, m_name{ name }
    {
        std::cout << "Employee " << m_name << " created.\n";
    }

    // Use a delegating constructor to minimize redundant code
    Employee(const std::string &name) : Employee{ 0, name }
    { }
};

Resetting class


default値でclassを返す場合は、次の操作を行います.
#include <iostream>

class Foo
{
private:
    int m_a{ 5 };
    int m_b{ 6 };


public:
    Foo()
    {
    }

    Foo(int a, int b)
        : m_a{ a }, m_b{ b }
    {
    }

    void print()
    {
        std::cout << m_a << ' ' << m_b << '\n';
    }

    void reset()
    {
        *this = Foo(); // create new Foo object, then use assignment to overwrite our implicit object
    }
};

int main()
{
    Foo a{ 1, 2 };
    a.reset();

    a.print();

    return 0;
}