Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

default constructor 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 am getting an error : cannot 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 error?

like image 637
lllook Avatar asked Dec 05 '22 22:12

lllook


1 Answers

What other way are you searching? In any case you have to define the default constructor if you are going to use it.

For example you could define your class the following way

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

Or you have to define the constructor explicitly

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

And one more example

class T
{
    public:
    T() : T( 0 ) {}
    T(int h){item = h;}
    int item;
};
like image 104
Vlad from Moscow Avatar answered Dec 31 '22 00:12

Vlad from Moscow