Three Diag
Three Diag

Reputation: 585

C++ default constructors absence and I cannot compile

I have this very simple class

class myclass {

public:
    int id;
    double x, y, z;

    myclass() = default; // If I omit this line I get an error
    myclass(int ID, double X, double Y, double Z): id(ID), x(X), y(Y), z(Z) {};
};

If I omit the line with the line myclass() = default; and then attempt at creating one object

#include <vector>
using namespace std;
int main() {

    int ID = 0;
    double X = 1.0, Y = 2.0, Z = 3.0;
    vector<myclass> a_vector(10);

    myclass an_object(ID,X,Y,Z);

    return 0;
}

I get an error no matching function for call to ‘myclass::myclass().

Why does this happen? When is it mandatory to specify the constructor taking no parameter as default?

This is probably a very easy question, but other questions on constructors seemed aimed at very specific issues with constructors, so I thought it might be worthwhile.

Upvotes: 0

Views: 1107

Answers (3)

Once you provide any constructor(s), the compiler stops providing other ones for you - you become in full control. Thus when you have one that takes some parameters, the one that takes no parameters is not provided anymore.

Upvotes: 7

Mark Ransom
Mark Ransom

Reputation: 308140

The problem is in the vector of myclass - vector has many methods that will use the default constructor. If you provide your own constructor as you did, the usual default constructor does not get generated for you. By adding the declaration with = default, you forced the compiler to generate the missing default. You could also define your own default constructor if the automatically generated one isn't sufficient, but there's no way to use a vector without one.

Upvotes: 2

Yasser Sobhy
Yasser Sobhy

Reputation: 155

because you didn't specify access modifiers for the second constructor, so it's private by default

simply add public: to your constructors

class myclass
{

int id;
double x, y, z;

public:

//myclass() = default; // If I omit this line I get an error
myclass(int ID, double X, double Y, double Z): id(ID), x(X), y(Y), z(Z) {};

};

Upvotes: 0

Related Questions