Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default argument of type "const char *" is incompatible with parameter of type "char *"

Tags:

c++

So I got this code from my teacher but it doesn`t work combined with other code, it works only if it is separatly in a project. The whole code works great, less this part

"Notes" is an other class which works perfectly

class student
{
    char name[30];
    notes marks;
public:
    student(int = 8, char* =" "); //HERE IS WHERE I GOT THE PROBLEM, AT HIS CHAR*
    ~student();
    void read_name();
    void read_marks();
    void modif_mark(int, double);
    void print();
    void check_marks();
};

/*...
  ...
  ...
*here is a lot of code working great*
  ...
  ...
  ...
*/

student::student(int nr_marks, char* sir) :
    marks(nr_marks)
{
    strcpy_s(name, sir);
}
like image 913
Iulian B. Avatar asked Apr 18 '19 18:04

Iulian B.


2 Answers

Depending on compiler, C-style string literals may be allocated in readonly memory. Thus they are const char[N+1] (N is the string length) (which is implicitly convertible to const char* because of array to pointer decay).

The problem you're having is that it's illegal to drop const qualifiers (with the exception of the infamous const_cast or equivalent C-style cast).

Since you're only reading from sir, you can fix this by making sir be const char* instead, which doesn't violate const:

class student {
...
student(int = 8, const char* =" "); // problem solved
...
};

student::student(int nr_marks, const char* sir) : // remember to change it here as well
    marks(nr_marks)
{
    strcpy(name, sir);
}
like image 193
Cruz Jean Avatar answered Nov 19 '22 09:11

Cruz Jean


Below is the error version

print_results("C = ", c);

Below is the Solved Version

print_results((char*)"C = ", c);
like image 4
Niroshan Ratnayake Avatar answered Nov 19 '22 11:11

Niroshan Ratnayake