Ke Xu
Ke Xu

Reputation: 1

How to initial a cstring in constructor in c++?

My homework requires using cstring to hold full name, so in header file I have

private:
char fullName[50];

In my cpp file I have two constructor

Employee_C::Employee_C(){
fullName = "";}
Employee_C::Employee_C(char name[]){
fullName = name;}

But it gives me error line, it says expression must be a modifiable value/

What's wrong with my code?

Upvotes: 0

Views: 1127

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311038

In the both constructors

Employee_C::Employee_C(){
fullName = "";}
Employee_C::Employee_C(char name[]){
fullName = name;}

the lines

fullName = "";
fullName = name;

are assignment statements. But arrays do not have the copy assignment operator.

What you need is the following

#include <cstring>

//...

Employee_C::Employee_C() : fullName { "" }
{
}

and

Employee_C::Employee_C( const char name[] )
{
    strncpy( fullName, name, sizeof( fullName ) );
    fullName[sizeof( fullName ) - 1] = '\0';  
}

Here is a demonstrative program.

#include <iostream>
#include <cstring>

class Employee_C
{
public:
    Employee_C();
    Employee_C( const char name[] );
    
    friend std::ostream & operator <<( std::ostream &os, const Employee_C &employee )
    {
        return os << employee.fullName;
    }
private:
    char fullName[50];  
};

Employee_C::Employee_C() : fullName { "" }
{
}

Employee_C::Employee_C( const char name[] )
{
    strncpy( fullName, name, sizeof( fullName ) );
    fullName[sizeof( fullName ) - 1] = '\0';  
}

int main() 
{
    Employee_C employee1;
    Employee_C employee2( "Ke Xu" );
    
    std::cout << employee1 << '\n';
    std::cout << employee2 << '\n';

    return 0;
}

The program output is

Ke Xu

Upvotes: 1

Related Questions