How to return a const char*reference?

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?
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
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
thanks!
Topic archived. No new replies allowed.