0

I want to fill an array that's a member of a class with data. Do I have to create a function that populates it, or is there a way that I can just enter the values directly?

class example
{
private:
    struct exm {
        int everything[3];
    };

public:
    exm demo;

    void output();
    void populate();
};

If not would this work?

void example::populate() {
    demo.everything[0] = 1;
    demo.everything[2] = 1;
    //and so on... (could probably use a for loop)
}
leemes
  • 44,967
  • 21
  • 135
  • 183
  • 1
    possible duplicate of [C++: constructor initializer for arrays](http://stackoverflow.com/questions/2409819/c-constructor-initializer-for-arrays) – Brandon Haston Jan 14 '14 at 23:43
  • 1
    `int everything[3] = {1, 1, 1};` – BWG Jan 14 '14 at 23:48
  • 1
    @BrandonHaston: Close, but not quite. That question refers to initializing arrays of arbitrary objects. While we can't do this (easily?) for arbitrary objects, we *can* for primitive types like `int`. – AndyG Jan 14 '14 at 23:50

1 Answers1

0

Since demo is a public member you can access it directly or you can create a member function to set values.

#include <iostream>

class example
{
  private:
     struct exm {
        int everything[3];
     };

  public:
    exm demo;
    void output();
    void populate(){
      demo.everything[2] = 1;
    }
};

int main() 
{

  example Test;

  Test.demo.everything[0] = 5;
  Test.populate();

  std::cout<< Test.demo.everything[0]; //outputs 5
  std::cout<< Test.demo.everything[2]; //outputs 1

  return 0;
}

`

Andrew L
  • 1,164
  • 12
  • 20