Jens
Jens

Reputation: 141

Initialize const variable in constructor after changing it

I have a Client class, which receives an std::string variable called emailAdress. This is what the code looks like now, and it works:

private:
    const std::string email;

Client::Client(std::string emailAddress) : email{emailAddress}
{

}

Now, I want to check if the email contains characters like an @ or a valid name with no strange characters. I want to do this with regex. Now, my question is, how do I initialize the const std::string email variable after changing the parameter variable? It says it doesn't want to because it is a const variable, that is why it is in the initialization list of the constructor right now.

Upvotes: 1

Views: 401

Answers (1)

super
super

Reputation: 12928

You can pass the parameter to a function, and let the function return the modified string.

class Client {
private:
    const std::string email;
    static std::string validateEmail(std::string email) {
        // ...
        return modifiedEmail;
    }

public:
    Client::Client(std::string emailAddress) : email{validateEmail(std::move(emailAddress))}
    {

    }
};

Upvotes: 4

Related Questions