Home > OS >  Error C2280 : Class::Class(void) : Attempting to reference a deleted function
Error C2280 : Class::Class(void) : Attempting to reference a deleted function

Time:09-21

So, I am working on a project, and I have two files in this project: main.cpp, matrix.h

The problem is that My code seemed to work perfectly a few hours ago, and now it doesn't

main.cpp:

#include <iostream>
#include "matrix.h"
#include <vector>
int main() {
    Matrix f;
    f.create(10, 1, {3, 4, 5, 6, 7, 8, 9});
}

matrix.h:

#pragma once
#include <iostream>
#include <string>
#include <Windows.h>
#include <vector>
class Matrix {
public:
    const size_t N;
    bool ifMatrixCreated;
    const char* NOTENOUGH = "The size of the array should match to the width*height elements";
    std::vector<int> arr;
    int w, h;
    void create(int width, int height, const std::vector<int> a) {
        w = width;
        h = height;
        if (a.size() != width * height) {
            ifMatrixCreated = false;
            std::cout << "bello";
        }
        else {
            ifMatrixCreated = true;
            arr = a;
            std::cout << "hello";
        }
    }
};

And when I compile, it generates this error (Using VS2019):

Error   C2280 | 'Matrix::Matrix(void)': attempting to reference a deleted function  Matrix | Line 5

It keeps saying that "The default constructor of Matrix cannot be referenced - It is a deleted function"

Can you help solve this error?

Thanks in advance.

CodePudding user response:

Here is the correct working example. The error happens because every const data member must be initialized. And

The implicitly-declared or defaulted default constructor for class T is undefined (until C 11)defined as deleted (since C 11) if any of the following is true:

  • T has a const member without user-defined default constructor or a brace-or-equal initializer (since C 11).
#pragma once
#include <iostream>
#include <string>
//#include <Windows.h>
#include <vector>
class Matrix {
public:
    //const size_t N;//this const data member must be initialised
    const size_t N = 6;
    bool ifMatrixCreated;
    const char* NOTENOUGH = "The size of the array should match to the width*height elements";
    std::vector<int> arr;
    int w, h;
    void create(int width, int height, const std::vector<int> a) {
        w = width;
        h = height;
        if (a.size() != width * height) {
            ifMatrixCreated = false;
            std::cout << "bello";
        }
        else {
            ifMatrixCreated = true;
            arr = a;
            std::cout << "hello";
        }
    }
};
  • Related