Constructor Overloading in C++

Node(Game(),v); in your constructor doesn’t do what you expected. It just creates a temporary without using it and makes no effect. Then it immediately destructs that temporary when control flows over the ;.

The correct way is initializing the members in each constructor. You could extract their common code in a private init() member function and call it in each constructor like the following:

class Foo {
    public:
        Foo(char x);
        Foo(char x, int y);
        ...
    private:
        void init(char x, int y);
};

Foo::Foo(char x)
{
    init(x, int(x) + 3);
    ...
}

Foo::Foo(char x, int y)
{
    init(x, y);
    ...
}

void Foo::init(char x, int y)
{
    ...
} 

C++11 will allow constructors to call other peer constructors (known as delegation), however, most compilers haven’t supported that yet.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)