Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

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

ID: 653146 • Letter: C

Question

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.

Explanation / 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];

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote