You said the function returns just a single character yet you are trying to return a character array. You can't have it both ways. What you should have done is char* getEmpName()const -- notice there is a * after char to indicate it will return an array of characters.

Hi, sorry to calling back to life this old post, but I still get error even if I tried to do as you said. I have a declaration in a class which is

class Bla{
private:
   char date[9];
public:
   char* ReturnDate(const Bla& blabla);
};

char* Bla::ReturnDate(const Bla& blabla);{
   return blabla.date;
}

The error is this

error C2440: 'return' : cannot convert from 'const char [9]' to 'char*'

Recommended Answers

All 3 Replies

mmm, if the whole point is avoiding accidental changes to Bla's date field then you could use const_cast.

http://www.cppreference.com/wiki/keywords/const_cast

char* ReturnDate(Bla const& blabla)
    { 
        //strcpy_s(blabla.date,8,"assssde");  <- This would give you a compiler error.
        return const_cast<char*> (blabla.date);
        
    }

Don't just trust me. Do some research. It's been some time since I fiddled with this and my memory is rusty. I'll look into this later, If I can

First, that semicolon on line 8 (between the end of your method implementation and the curly brace) is going to be a problem....

"blabla.date" is "const char *". So, one of 2 things: either cast the return value as (char *), so it will match the method prototype:

return (char *)blabla.date;

or, change the method prototype to return a type of "const char *":

class Bla{
private:
   char date[9];
public:
   const char* ReturnDate(const Bla& blabla);
};

const char* Bla::ReturnDate(const Bla& blabla){
   return blabla.date;
}

Second one Worked and I understood the reason: Thank you!
Just to explain to future beginner readers:

I declared a const char[] array; To return an array you must declare the function, whatever type it is, as

*type function(parameters){
   return parameter;
}

The only problem here was: that was a constant char, so you must declare your function as

const *type function(etc....)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.