-1

I am trying to create a class (foo) with a private member array. This class will be used as a private member of another class (foo2) in the constructor of which the array will be initialized.

example.h:

class foo{
private:
    int* ary;
public:
    foo(int*);
    ~foo();
}

example.cpp:

foo::foo(int* b){
ary = b;
}

useOfExample.h

class foo2{
private:
  foo my_foo;
public:
  foo2();
  ~foo2();
}

useOfExample.cpp

foo2::foo2() : myfoo({2,3}){}

I am kind of a noob in C++ and I realize what I am asking may not be really clear so in other words I need foo2 to have a member foo of which the array will be set to [2,3].

loogikos
  • 63
  • 1
  • 8
  • 1
    That's not an array, that's a pointer to an integer (I know you can treat them almost the same). Why would you do something this horrible with pointers in C++ when you could use an STL class? Do you know the scope of that `{2,3}` without checking? Can it go out of scope while `myfoo` is still pointing at it? – John3136 Dec 18 '16 at 22:16
  • 1
    Arrays are not pointers, pointers are not arrays and the standard dynamic array in C++ is `std::vector`. You should use that. If you can't, you need to review your course material (or whatever it is you are learning from) to figure out what you are actually supposed to do here. – Baum mit Augen Dec 18 '16 at 22:17
  • `int* ary;` => `int ary[2];` or `std::array ary;`. Then it will be an array , not an uninitialized pointer. – Paul Rooney Dec 18 '16 at 22:19
  • What I need is to create a dynamic array, which will get its size from the use of foo2. For example there can be another class foo3 with an initialization of its respective "myfoo" being "myfoo({2,3,4,5,6,7})" and so on. And no I cannot use vectors... – loogikos Dec 18 '16 at 22:29

1 Answers1

0

Take a look at: Static array vs. dynamic array in C++

You cannot use the {...} syntax to initialize a dynamic array; you need to fill it up manually.

Community
  • 1
  • 1
user
  • 675
  • 4
  • 11
  • thanks for the answer, I thought it might be possible because I believed that by doing so I was specifying something, like when initializing an integer, not realizing that the array continues to be dynamic after that. – loogikos Dec 18 '16 at 23:38