0

I have a pointer to array of objects. It looks like:

MyClass *myClass[ 10 ];
myClass[ 0 ] = new MyClass(); // init for each of myClass[0..9]
myClass[ 0 ]->field1 = "hello";

How can I pass "myClass" to a function by reference? I tried a few cases but it didn't work.

2
  • 7
    That's an array of pointers. You should prefer std::array<MyClass, 10> especially when passing it into a function. Commented Jul 11, 2013 at 21:53
  • it's my fault. I meant myClass instead of obj. Commented Jul 12, 2013 at 9:19

1 Answer 1

5

If you really must use an array, then

template<size_t N >
void foo(MyClass (&arr)[N] )
{
  // Access arr[i], size is N
}

...

foo(myClass);

Otherwise, use an std::array

template<size_t N >
void foo(std::array<MyClass,N>& arr )
{
  // Access arr[i], size is N or arr.size()
} 

...

std::array<MyClass, 10> myClass = ....;
foo(myClass);

I would not call an array "myClass" though.

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

Comments

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.