Constructors

The original thinking and design of C++ constructors was to facilitate the creation and initialisation of objects. It was desired that user defined types should look and act like primitive/native types.

So if you can do this

int x = 4;

x += 3;

You should be able to do

Widget w = 4; // assuming Widget is a class

w += 4; // this type of behaviour should syntactically sound as well as semantically correct

Constructor with single parameter

// type-conversions.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include <iostream> using namespace std; class Widget { public: Widget(int x) :_val(x) { cout << "Widget::Widget constructed with " << x << endl; } Widget(const Widget& rh) { _val = rh._val; } private: int _val; }; int main() { Widget w = 1; auto w2 = Widget{ 2 }; Widget w3 = Widget{ 3 }; w2 = 99; std::cout << "Hello World!\n"; }

What happens when line 31 executes?

Correcting the unwanted behaviour

Remember, the intention of constructor is to allow user defined types should look and act like primitive/native types. So what may look like odd behaviour is somewhat correct. However, there are times when this can cause serious issues, especially if an object contains pointers to other other objects.

Change the single parameter constructor to

explicit Widget(int x) :_val(x) { cout << "Widget::Widget constructed with " << x << endl; }