Search code examples
c++default-constructor

Create a default constructor when using const strings


I have a class that looks like this:

Person(int pID,
    int zipCode,
    float ySalary,
    const string& fName,
    const string& mName,
    const string& lName)

When I try to create a default constructor as shown below:

Person::Person(void){
    zipCode = NULL;
    pID = NULL;
    ySalary = NULL;
    fName = "";
    mName = "";
    lName = "";
}

I get an error saying there is no operator "=" that matches const std::string = const char[1];


Solution

  • You need to use the member initializer list to initialize const reference member variables:

    Person::Person(void) :
        zipCode(NULL) ,
        pID(NULL) ,
        ySalary(NULL) ,
        fName("") ,
        mName("") ,
        lName("") { 
    }
    

    I'd recommend always to use the member initializer list syntax, preferred to assignments in the constructor body. See here for example: What is the advantage of using initializers for a constructor in C++?