C++ and C – Functions Returning Pointers Explained

cclasspointers

C++ noob here. I have a very basic question about a construct I found in the C++ book I am reading.

// class declaration
class CStr {
  char sData[256];
 public:
  char* get(void);
};

// implementation of the function
char* CStr::get(void) {
  return sData;
}

So the Cstr::get function is obviously meant to return a character pointer, but the function is passing what looks like the value (return sData). Does C++ know to return the address of the returned object? My guess would have been that the function definition would be return &sData.

Best Answer

For C and C++, array's degrade to pointers. An array cannot be returned as the value of a function, only a pointer can be returned. Returning the array is equivalent to returning the address of the first element of the array:

return &sData[0];