Home > Software engineering >  How to pre-initialize an object array in c like an actual array?
How to pre-initialize an object array in c like an actual array?

Time:05-03

DISCLAIMER Good day, I am a novice programmer so please don't judge me if I have any mistakes that may be obvious or not.

I have a code that looks like this.

class Book{
public:
    string author;
    string title;
    int yearPub;
}

int main(){
    Book books[999];
}        

However, I don't know how to predefine a certain amount of titles and authors like how they are defined in other variable types like this:

string author[99] = {"asdf","asf","asdff"};
int x[] = {9,10,19};

I tried initializing a constructor and did this:

class Book{
public:
...
    Book(string AUTH, string TTL, int YROP){
        author = AUTH;
        title = TTL;
        yearPub = YROP
    }
...
}
int main(){

Book books[999] = Book({"author1","author2"},{"title1","title2},{2022,2022});
return 0;
}

But it doesn't work. Do you know any way to do this?

CodePudding user response:

Assuming you don't have a custom constructor, you can do this:

Book books[999] = {{"author1","author2"},{"title1","title2"}};

If you do want a custom constructor, you'll also need to add the second constructor: a default one (thanks @WhozCraig) that will be used for array elements that don't have their own initializers: Book() {}.


Some alternative syntax variants:

Book books[999] = {Book{"author1","author2"},Book{"title1","title2"}};
Book books[999] = {Book("author1","author2"),Book("title1","title2")};

The latter required the two-argument constructor until C 20.


Also consider using std::vector to avoid wasting storage on non-existent books`.

CodePudding user response:

In the both cases you can write

Book books[999] = { { "author1", "title1" }, { "author2", "title2"} };

Provided that in the second case (when the construct with two parameters is defined) there is also declared the default constructor as for example

class Book {
public:
    Book( std::string author, std::string title )
        : author( std::move( author ) ), title( std::move( title ) )
    {
    }
    Book() = default;        
    
    std::string author;
    std::string title;
};

In the first case when your class is an aggregate you can also write

Book books[999] = { "author1", "title1", "author2", "title2" };

or even

Book books[999] = { "author1", "title1", { "author2", "title2" } };

or

Book books[999] = { { "author1", "title1" }, "author2", "title2" };
  • Related