Returning refernce to a pointer

Hello, I'm trying to return a dynamically created char pointer to be used by an overloaded operator<< function as such:

char *string = new char[size];
string[0] = NULL; // empty string

ostream &operator<<( ostream & output, const String & str )
{
output << str.getString();
return output;
}

char &String::getString() const
{
char *str = &string;
return &str;
}


ERROR: error C2440: 'initializing' : cannot convert from 'char *const *' to 'char *' ERROR: error C2440: 'return' : cannot convert from 'char *' to 'char &'

Basically, I want to return a reference so that the user can not use the returned pointer to change to data in string.
Last edited on
You want to return a const char*.

1
2
const char* String::getString() const
{  return string; }


Whats the difference between const in front and const at the end, and why would you need both?
The return type is const char*.

The const at the end says the member function itself is const, which means that the member function will not modify any of the member variables of the object. In this case, it's just returning a pointer.

EDIT: If you are concerned about const-ness of data (as you should be), then it is imperative you learn to write const-correct code. The only thing worse than never using the keyword const is using it incorrectly, because you end up with a nightmare of const-correctness compile errors that can be very hard to fix.
Last edited on
So let me get this straight, any function that ends with const can not change any of the variables that it works with? Or is that just the case when its part of a class? And would there really be any need for the ending const statement if the code within the function didn't try to modify the member variables anyways?
If its not trying to modify member variables, then there is no need. Programmer still use it for a good practice.

When you say "modify the member variables" it means the function has to be a part of the class. Doesn't it? :)
Last edited on
Only member functions can be const.

From a technical standpoint, your program will work with or without being const correct.

However, there are two main reasons to get into the habit of writing const correct code:
1) Compilers can and do generate better code when they know a member function will
not modify members of the class.
2) It provides the users of your code with the guarantee that they can call said function
and it will not modify the object. In effect, it is part of the API.
Thanks for the clarification. =)

For n4nature, I meant any function, I only stated "member variables" in the last part of my question. Sorry for the confusion. I didn't know at the time that const functions could only be declared in a class. =)

Thanks again.
Last edited on
Topic archived. No new replies allowed.