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];
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.