C2664 'cMan::cMan(char *,char *,double,int)': cannot convert argument 1 from 'const char [6]' to 'char *'

310 Views Asked by At

Hello I am just learning C++. I have this code but when I try to build the solution error from title shows up. Any ideas how to fix that?

class cMan
{
public:
    cMan(char *chFirstName, char *chLastName, double dWeight, int iHeight);
    ~cMan();
    void vWriteMembersValues();

private:
    char chFirstName[5];
    char chLastName[5];
    double dWeight;
    int iHeight;
    
};

cMan::cMan(char *chFirstName, char *chLastName, double dWeight, int iHeight)
{
    for (int i = 0; i < 5; i++)
    {
        this->chFirstName[i] = chFirstName[i];
        this->chLastName[i] = chLastName[i];
    }
    
    this->dWeight = dWeight;
    this->iHeight = iHeight;
}

cMan::~cMan()
{
    delete this;
}

void cMan::vWriteMembersValues()
{
    for (int i = 0; i < 5; i++)
    {
        cout << this->chFirstName[i];
        
    }
    
    for (int i = 0; i < 5; i++)
    {
        cout << this->chLastName[i];
        
    }
    
    cout << " " << this->dWeight;
    cout << " " << this->iHeight;
    
}
int main()
{
    cMan cmI("Michal", "Stanko", 83.5, 200);
    
    cmI.vWriteMembersValues();
    
    cout << endl;
    
    cmI.~cMan();
    
    cin.get();
    cin.get();
    
    return 0;
}

I don't know much about programming but if anyone would explain this to me as easy as possible i would be glad.

3

There are 3 best solutions below

2
On

The issue is const.

Try taking a const char * instead of a char *

0
On

String literals are const char[] arrays, so you need to update your cMan() constructor to take const char* pointers instead of char* pointers. Or else, use std::string instead.

0
On

You are calling the constructor

cMan cmI("Michal", "Stanko", 83.5, 200);

passing to it string literals.

In C++ opposite to C string literals have types of constant character arrays. Used as argument expressions they are implicitly converted to pointers to their first characters of the type const char *

Thus if you are going to use string literals as arguments of the constructor then declare it like

cMan( const char *chFirstName, const char *chLastName, double dWeight, int iHeight);

Pay attention to that the used string literals in this declaration

cMan cmI("Michal", "Stanko", 83.5, 200);

have more characters then the corresponding initialized data members of the class.

If you will pass string literals with length that less than the size of the arrays declared as data members then this loop

for (int i = 0; i < 5; i++)
{
    this->chFirstName[i] = chFirstName[i];
    this->chLastName[i] = chLastName[i];
}

can be a reason of undefined behavior when you will try to use the data members.

So to avoid the undefined behavior it is better to store strings in the data members. You could declare the data members as having the type std::string instead of the type char[5].