The default constructor is not generated?

#include <iostream>    
using namespace std;

class T
{
    public:
    T(int h){item = h;}
    int item;    
};

int main()
{
    T a;
    cout << a.item << endl;
    return 0;
}

I get an error: I can’t find T::T(), I know that the compiler does not generate an implicit constructor when I declare constructors with parameters, and this could be fixed by changing the constructor parameter to int h = 0, but is there any other way to get rid of the error?

+4
source share
2 answers

What other way are you looking for? In any case, you need to define a default constructor if you intend to use it.

For example, you can define your class as follows

class T
{
    public:
    T() = default;
    T(int h){item = h;}
    int item = 0;
};

Or do you need to explicitly define the constructor

class T
{
    public:
    T() : item( 0 ) {}
    T(int h){item = h;}
    int item;
};

And another example

class T
{
    public:
    T() : T( 0 ) {}
    T(int h){item = h;}
    int item;
};
+8
source

, . [class.ctor], :

X X, . X , (8.4).

, . , . :

T() = default;      // leaves item uninitialized
T() : item(0) { }   // initialize item to 0

, :

T(int i = 0) : item(i) { }

:

T a(42);
+5

All Articles