Arrays in Classes

Happy Friday everyone. This program is 1/3 complete, but it still runs. I have to define a class and declare an array of strings with 7 colors. I set up a default constructor and initialized my array there, and then made a function to print the members of the array, but this part is not working. Can someone tell me why? I know I can just declare a string array in the int main and make a parameterized function in the class but surely there must be a way to do it the other way?

The rest of the program is creating a function that takes a random index member and couts it, but Im gonna try that on my own.

Thanks.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

#include <iostream>
#include <string>
using namespace std;

class Rainbow
{
    
private:
    
    string myColors[7];
    
public:
    
    Rainbow() {
                string myColors[7] = { "Red", "Blue", "Orange", "Purple", "Green", "Violet", "Yellow" };
              }
    void printRainbow()
        {
        for (int i = 0; i<7; i++) {
            cout << myColors[i] <<endl<< endl;
        }
    }
};

int main()
{
    Rainbow R1;
    
    R1.printRainbow();
}
Last edited on
Line 16:
Should be just:
 
myColors[7] = { "Red", "Blue", "Orange", "Purple", "Green", "Violet", "Yellow" };
I tried that but i get this error:

"No viable overloaded '='"
Oh right, silly me.
 
myColors[7] = { "Red", "Blue", "Orange", "Purple", "Green", "Violet", "Yellow" };

This will try to access the element at index 7, which is out of bounds and will result in undefined behaviour.

To initialise the array, just run a loop and set each element to what you desire.

Alternatively, you could do this:
1
2
3
4
private:
    
    static constexpr string myColors[7] = { "Red", "Blue", "Orange", "Purple", "Green", "Violet", "Yellow" };
    

Last edited on
I was able to initialize it in a separate function with the loop, but can I do this in a default constructor? With no parameters.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

#include <iostream>
#include <string>
using namespace std;

class Rainbow
{
    
private:
    
    string myColors[7];
    
public:
    
    Rainbow()
    : myColors { "Red", "Blue", "Orange", "Purple", "Green", "Violet", "Yellow" }
    {}
    void printRainbow()
    {
        for (int i = 0; i<7; i++) {
            cout << myColors[i] <<endl<< endl;
        }
    }
};

int main()
{
    Rainbow R1;
    
    R1.printRainbow();
}


You have to use an initialization list to conveniently assign all indices.
The problem is that the array is already initialized in the body of the constructor, so you can't do the array assignment after it's already been initialized.
Last edited on
Topic archived. No new replies allowed.