My C++ overloading does not act as I assume it should:
#include "Node.h"
#include <iostream>
Node::Node()
{
cout << "1" << endl;
Node(Game(), 0.0);
}
Node::Node(double v)
{
cout << "2" << endl;
Node(Game(),v);
}
Node::Node(Game g, double v)
{
cout << "3" << endl;
numVisits = 0;
value = v;
game = g;
}
And the output from:
Node n(16);
cout << n.value << endl;
is 0, when it should be 16.
What am I doing incorrectly?
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:
C++11 will allow constructors to call other peer constructors (known as delegation), however, most compilers haven’t supported that yet.