0

Been trying to get this to work for hours with many different methods but still can't get it to work...

Main class:

WinHandle wh;
int* myarr;
myarr = wh.getpos;
cout << "left: " << *(myarr) << endl;

WinHandle.cpp class:

int* WinHandle::getpos(){
  int pos[4];
  //code
  pos[0] = 2;
  //code

  return pos;
}

WinHandle.h file:

int* getpos();

That's just my last method, tried various others to no avail. Any help?

Keep getting

non-standard syntax; use '&' to create a pointer to member

and

cannot convert from 'int *(__thiscall WinHandle::* )(void)' to 'int *'
4
  • 2
    1. myarr = wh.getpos();. 2. You're trying to return a pointer to local variable so it will become dangled (didn't you get any compile warnings?). Commented Jul 10, 2016 at 2:11
  • 1
    Possible duplicate of C++ return array from function Commented Jul 10, 2016 at 2:16
  • Or How to return local array in C++? Commented Jul 10, 2016 at 2:18
  • why are you using pointers in this case? If you're using C++, it's best std::array, or std::vector, or one of other beautiful containers. Commented Jul 10, 2016 at 9:55

3 Answers 3

2

A plain array cannot be returned directly from a function.

Use std::array, instead.

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

Comments

1

Your immediate source of compilation error is wrong syntax. When you are calling the function, you need to call it with parenthesis: wh.getpos(). However, this is a lesser of a problem. A much bigger problem is that you are returning an array which is local to your function. This won't do, this array will be destroyed once you exit the function, and you will end up with a pointer to deleted object. Say 'Hi' to undefined behavior.

To fix the problem, you need to return either std::vector or std::array.

3 Comments

Or make the array being returned a member of WinHandle. Then the pointer returned by wh.getpos() is valid for as long as wh continues to exist.
@Peter, might be a valid option depending on the design of the class.
Sure. That's why I suggested it as an additional option to fix the problem.
0

The best solution is to use std::array (or std::vector) because it's the most flexible. Otherwise, you could create the array outside the method, then use a reference parameter to operate on it inside wh.getpos().

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.