1

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.

7
  • 2
    If you need to change it then why is it const? Commented Jan 14, 2021 at 14:19
  • It doesn't need to get changed later on, it should be initialized in the constructor and then be const Commented Jan 14, 2021 at 14:20
  • 2
    email{SomeFunctionThatPerformsNecessaryChanges(emailAddress)}? Commented Jan 14, 2021 at 14:21
  • Ooooh that makes so much sense thank you!! Commented Jan 14, 2021 at 14:21
  • 3
    const data members come with several drawbacks and are generally not worth it. It almost always makes the type non-assignable and non-moveable. It is often best to maintain the invariance using the class interface. Make the member private and don't provide a setter. Commented Jan 14, 2021 at 14:24

1 Answer 1

4

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))}
    {

    }
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.