0
char* f() {
   cout << b;
   return "B::f";
}

Ok so I have this piece of code inside a class and I keep get this error

'return': cannot convert from 'const char [5]' to 'char*'

I tried some online compilers and it works just fine .

So why is this happening ?

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • 4
    "B::f" is of type `const char *` - obviously not the same type your function returns (`char *`). Also, why are you not using `std::string`? – Jesper Juhl Jun 23 '18 at 14:17
  • Thanks for answering ! Im a student in informatics and Im not very well accustomed to correctly using the std , I just used using namespace std; at the begining of the code. Also the f() is a virtual function "virtual char* f() = 0;" and changing it to const char * would trow me an error . I was just wondering why this is only happening in VS . In any other compiler I tried it works just fine. The task requires me to use the virtual function as it is given. –  Jun 23 '18 at 14:27
  • 2
    Enable all warnings and you'll see all compilers complaining about that. and [`using namespace std` is not a good practice](https://stackoverflow.com/q/1452721/995714) – phuclv Jun 23 '18 at 15:02
  • See this https://stackoverflow.com/a/7440203/6414842 for a better explanation on why this happens. – R S Jun 23 '18 at 15:25
  • You mangled the error message pretty badly. Fixed to match the snippet, verify that the edit is good. And no, C++ forbids converting a string literal (aka const char[]) to char[] or char*, that is a const violation. C does allow it for histerical reasons. – Hans Passant Jun 23 '18 at 16:35

1 Answers1

1

The return type of this function indicates that the storage it points to can be changed. However you return a literal, which does not allow modifications.

Change the signature to

const char* f();

and it will work.

Kit Fisto
  • 4,385
  • 5
  • 26
  • 43