lllook
lllook

Reputation: 749

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?

Upvotes: 4

Views: 3290

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

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;
};

Upvotes: 8

Barry
Barry

Reputation: 302842

There is no default constructor because you provided one yourself. From [class.ctor], emphasis mine:

A default constructor for a class X is a constructor of class X that can be called without an argument. If there is no user-declared constructor for class X, a constructor having no parameters is implicitly declared as defaulted (8.4).

Since there is a user-declared constructor, there's no implicitly declared default. So you have three choices. You can explicitly declare a default:

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

Or you can provide a default argument like you suggested:

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

Or you can simply use the constructor you created:

T a(42);

Upvotes: 7

Related Questions