For your question as asked
// in .h
class Foo
{
private:
char charArray[32];
public:
const char *getCharArray() const;
};
// in .cpp
// include the header!
const char *Foo::getCharArray() const
{
return charArray;
}
Bear in mind that the above returns a pointer to private data of the class Foo
(rather than a copy of the array). The const
qualifiers prevent the caller from (deliberately or accidentally) using the returned pointer to manipulate private data of class Foo
.
However, your approach (using a raw array of char
in a class) is considered a poor approach in C++. It tends to be harder to use too.
A better approach would be to use a standard container rather than a raw array.
// in .h
#include <array> // C++11 and later
class Foo
{
private:
std::array<char, 32> charArray;
public:
std::array<char, 32> getCharArray() const;
};
// in .cpp
// include the header!
std::array<char, 3> Foo::getCharArray() const
{
return charArray;
}
In this approach, the caller of Foo::getCharArray()
receives a COPY of the entire array, rather than a pointer or reference to private data of class Foo
. The caller can safely update the array it receives, and then later provide it back to class Foo
(e.g. via a setter). Whereas, with using a pointer and a raw array, more gymnastics is needed to achieve a similar effect.
Optionally, a const
reference to the std::array<char, 3>
can be returned in the above, which can avoid some unnecessary copying of complete objects.