1
class myObject{
private:
subOBJ* subList;
int size

public:
myObject(subOBJ list[]);
}

For example, my object looks something like this and I want to create an object that will do something with an array of subOBJs passed in.

myObject::myObject(subOBJ list[])
{
    size = sizeof(list);
    subList = new subOBJ[size];
    for(int i=0; i< size; i++){
        subList[i] = list[i];
    }
}

is it correct to design my constructor like so assuming the passed in array of subOBJs are valid.

Enlico
  • 23,259
  • 6
  • 48
  • 102
tofokevin
  • 37
  • 5
  • 2
    `size = sizeof(list);` -- This does not do what you think it does, as `list` is just a pointer. Why not simply use `std::vector subList`? – PaulMcKenzie Sep 25 '20 at 01:35

1 Answers1

1

In C++, you don't need to work with pointers in most cases. There are already classes that take care of that for you. Such as std::array<T> or std::vector<T>.

myObject(subOBJ list[]);

You need atleast one additional parameter: the length of/number of elements in the array.
in C++, passing arrays to functions doesn't pass the array, but the adress of the first element to it.
It is impossible to know the size within the function the array is passed to. Hence why you need to pass a second parameter length (number of elements) to it.

I recommend going for vector<subOBJ>(size is determined at runtime) or even array<subOBJ>(if size is known at compiletime).

Raildex
  • 3,406
  • 1
  • 18
  • 42