Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor Overloading in C++

Tags:

c++

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?

like image 225
sdasdadas Avatar asked Sep 07 '11 07:09

sdasdadas


People also ask

What are constructors overloading?

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.

What is constructor overloading with example?

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.

Why do we use constructor overloading in C++?

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.


2 Answers

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.

like image 153
Mu Qiao Avatar answered Sep 26 '22 08:09

Mu Qiao


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; } 
like image 40
Praetorian Avatar answered Sep 26 '22 08:09

Praetorian