'C++ Can't initialize dynamic array of structs [duplicate]

struct article {
    int uId;
    char uName[201];

    article(int Id, char* name) { uId = Id;
        for(int i=0;name[i]!='\0';i++)
        {
            uName[i]=name[i];
        }

    }
};

int main()
{
char Name[201];
int ID;
int N;
cin>>N;
article* articleArr = new article[N];  //error thrown on this line
/*Some code that creates ID and Name*/
articleArr[index] = article(Id, Name);
cout<<articleArr[index].uId<<' '<<articleArr[index].uName<<endl;


}

The problem I have with my code is that I can't dinamically create an array of structs. Compiler throws out an error "no matching function for call to 'article::article()" at the (article* articleArr = new article[N];) line. Before I started implementing dynamic initialization of array of structs it worked fine. I have to use char arrays, not allowed to use strings.



Solution 1:[1]

This line

article* articleArr = new article[N];  

Is trying to invoke the default constructor but you do not have one.

You need to add

struct article {
    int uId;
    char uName[201];
    article() {  
         /// whatever code is needed to initalize an empty article
    }
    article(int Id, char* name) { uId = Id;
        for(int i=0;name[i]!='\0';i++)
        {
            uName[i]=name[i];
        }

    }
};

c++ would normally automatically do this for yo , but because you gave a constructor c++ did not create any others

BTW - you should really use std::vector rather that a 'new'ed array, its much easier and safer to use

same is true for std::string instead of naked char *

Solution 2:[2]

article(int Id, char* name)

You have declared a constructor that accepts parameters. As a consequence, the class will not have an implicitly generated default constructor. Since you haven't defined a constructor either, the class is not default constructible.

new article[N]`

This default constructs an array of N instances of the class article. This is ill-formed because the class is not default constructible.

Potential solutions:

  • Define a default constructor.
  • Or don't default construct instances of the class.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 pm100
Solution 2 eerorika