0

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]; 
0

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Works fine for me, exactly as I wrote it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.