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
.
6
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];
3
Does C++ know to return the address of the returned object?
In this case, yes. An array’s name is a constant pointer to the first element in the array. So, when
char* CStr::get(void) {
return sData;
}
is executed, pointer to the first element of the array is returned. So, the caller can reference the array and do a traversal. Run the following code. You’ll see the output “hello, world”.
#include <iostream>
#include <string>
class CStr {
char sData[256];
public:
CStr(std::string str);
char* get(void);
};
CStr::CStr(std::string str) {
if (str.length() >= 256) {
sData[0] = 'n';
return;
}
str.append("n");
str.copy(sData, str.length());
}
char* CStr::get(void) {
return sData;
}
int main() {
CStr msg("hello, world");
char* str = msg.get();
while (*str != 'n')
std::cout << *str++;
return 0;
}
5
In C and C++ returning the name of an array is same as returning the Address of the first element in an array hence you can return the same address in three different ways :
return sData;
return &sData;
return &sData[0];
all the three statements return the same address.
1