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?
Constructor overloading in Java refers to the use of more than one constructor in an instance class. However, each overloaded constructor must have different signatures. For the compilation to be successful, each constructor must contain a different list of arguments.
The constructor overloading can be defined as the concept of having more than one constructor with different parameters so that every constructor can perform a different task. Consider the following Java program, in which we have used different constructors in the class.
Answer: Benefits of constructor overloading in C++ is that, it gives the flexibility of creating multiple type of objects of a class by having more number of constructors in a class, called constructor overloading. In fact, it is similar to C++ function overloading that is also know as compile time polymorphism.
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.
The feature you're trying to use is called delegating constructors, which is part of C++0x. Using that syntax your second constructor becomes
Node::Node(double v) : Node(Game(),v) { cout << "2" << endl; }
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