0

The below is just a brief part of my code. And when I run it, it gives me the warning that ISO C++ forbids converting string to char* for visual studio code and exits with code 1. Is there a way I can ignore the warning to run the code?


Class Airport
{
public:
    Airport(char *code, char *name);
}
Airport::Airport(char *code, char *name)
{
    airport_code = new char[20];
    strcpy(airport_code, code);
    airport_name = new char[20];
    strcpy(airport_name, name);
}
int main() {
    
    Airport *lax = new Airport("LAX", "LA");

}

I saw on other stackoverflow posts that changing char to const char will solve the problem. But because the values will need to be changed using other predefined functions, it won't be the answer that I need.

Judy
  • 11
  • 2
  • *"I saw on other stackoverflow posts that changing char to const char will solve the problem..."* Yes that(changing `char*` to `const char*`) is the solution. – Jason Dec 08 '22 at 08:18
  • You can **fix** the warning with the simple change of `char*` to `const char*`. Don't ignore warnings we see a large number of posts caused by beginners who ignored warnings. – john Dec 08 '22 at 08:19
  • 1
    When you have strings and use C++, forget about passing strings as "C" style char*. Use std::string instead.E.g. `Airport(const std::string& code, const std::string& name)`, with member variables also of type std::string. Raw pointers in C++ should be non-owning. (Have a look at "naked new" and "raw pointer" here : https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines) – Pepijn Kramer Dec 08 '22 at 08:20
  • Your comment about needing to change the values is wrong. Adding `const` to `name` and `code` does not mean that you cannot change your `airport_name` and `airport_code` arrays. – john Dec 08 '22 at 08:22
  • 1
    Also don't fall into the trap of "tool satisfaction". If a compiler gives you a warning it has a good reason for it. Don't work around it but really understand what it is telling you and fix the underlying issue. – Pepijn Kramer Dec 08 '22 at 08:24
  • "it won't be the answer that I need." why not ? You arent changing the contents of those strings in your code. You copy them to members. – 463035818_is_not_an_ai Dec 08 '22 at 08:27

0 Answers0