0

Having

class Foo {
public:
  static constexpr size_t WIDTH = 10;
  static constexpr size_t HEIGHT = 20;

private:
  int _data[HEIGHT][WIDTH];
}

I would to get my variable _data from a member function of this class, but I cant find the good prototype.

see @How to return a static array pointer but this syntax seems to dont work with member functions, it can't compile.
Also tried

int **getData() {
  return static_cast<int **>(_data);
}

But I dont think this is a good pratice.

1
  • cause it's useless to create an object for my case :") it's kinda related to optimizations, but that's not rly the question, Im kinda sure we can return this static array with some syntax.. Commented Jun 10, 2018 at 15:43

1 Answer 1

2

You can always return a pointer to the first element, like you did which is perfectly safe.

The better solution IMO would be to use std::array, which can be copied unlike C style arrays.

Another way would be to return a reference to the array:

auto& getData() { return _data; }

Without auto it would look like this:

int (&get())[HEIGHT][WIDTH] { return _data; }

You can always make it pretty with using:

using RefToArray = int(&)[HEIGHT][WIDTH];
RefToArray get() { return _data; }
Sign up to request clarification or add additional context in comments.

7 Comments

this cant compile by the way >< I though at start.. Is it compiling on your computer?
@lordjj Yes it does (see for example here). What did you do differently and/or what's the error?
@lordjj Oh wait, you need C++14 for this. Which version of C++ are you using?
It does compile, but when I call the function getData(), this comes out: use of ‘auto& GameMap::getData() const’ before deduction of ‘auto’. The instance of the concerned GameMap is already created, it justs break the compilation when I try to call getData()
I'm using C++ 17
|

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.