How to return a const char*reference?
Nov 7, 2009 at 5:00pm UTC
I want to return the pointer to the beginning of an array as a reference in a method. Something like this:
(const char *)& funct (void ); // This doesn't compile.
How can i do it?
Nov 7, 2009 at 5:04pm UTC
1 2 3
const char *& Obj::funct(void ){
return array_;
}
invalid initialization of non-const reference of type 'const char*&' from a temporary of type 'char*'
Last edited on Nov 7, 2009 at 5:04pm UTC
Nov 8, 2009 at 12:13am UTC
This does not work:
1 2 3 4 5 6 7 8 9 10 11 12 13
// Faulty
//Error: invalid initialization of non-const reference of type 'const char*&' from a temporary of type 'char*'
class Obj
{
public :
char array_ [5];
const char * & funct(void );
};
const char * & Obj::funct(void )
{
return array_;
}
This works:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
class Obj
{
public :
char array_ [5];
const char *const & funct(void );
};
const char *const & Obj::funct(void )
{
return array_;
}
int main()
{
Obj o;
const char * pp = o.funct();
}
**Before I forget - Please note that the compiler will may give a warning that you are returning a reference to a temporary object**
Last edited on Nov 8, 2009 at 9:57am UTC
Nov 9, 2009 at 10:03pm UTC
thanks!
Topic archived. No new replies allowed.