Search code examples
c++arraysclassdefault-value

class array default setting c++


I can't find any information on whether or not you can set default values for arrays created via a class and/or any syntax for arrays made via classes beyond mere creation. Please help.


// strings
#include <string> 

//normal setup
#include <iostream> 
#include <string> 
using namespace std; 

// multi array setup
class recordtype { 
public: 
    // array vars
    string namef; 
    string namel;
    char size; 
}; 
// array 
recordtype listof[11]; 

Solution

  • You can value-initialize all of the elements of the array using this syntax, eg:

    recordtype listof[11]();
    

    Which, in your example, will default-construct all of the string fields, and set all of the char fields to 0.

    Though, in this case, it would be better to give recordtype a default constructor to initialize its members as needed, and then let the recordtype listof[11]; syntax call that constructor on each element for you.

    Otherwise, you can specify actual values for specific elements, eg:

    recordtype listof[11]{ // or: = {
        {"name1", "name2", 'A'},
        {"name1", "name2", 'B'},
        // and so on...
    };
    

    In this case, any array element(s) that are not explicitly initialized will be value-initialized.