casperf1
casperf1

Reputation: 101

Initialising a constant string in a constructor? C++

//Person declaration
Class Person {
    public:
        Person();
        const String getName() const;
    private:
        const String name;
};

//Person definition
    #include "Person.h"
    Player::Player() {
    cout << "Enter name: ";
    cin >> name;
}

If I want to initialize the person's name upon creation of the class, using the default constructor and an initialization list, but with the constraint of name_ being a const, how can I go about doing this?

I don't believe an init list for name would work, considering that to my knowledge an init list sets the values upon creation, and with name being a const it wouldn't be modifiable at that point anymore.

So assuming I create a Person(); in another class, how can I initially set their name to const for the duration of that class instance's life time?

Upvotes: 0

Views: 4830

Answers (2)

Pete Becker
Pete Becker

Reputation: 76523

You can call a function as the initializer:

std::string get_name() {
    std::cout << "Name: ";
    std::string nm;
    std::cin >> nm;
    return nm;
}

Person::Person() : name(get_name()) {
}

Upvotes: 0

Del
Del

Reputation: 1319

Don't prompt for input in the constructor. Move the IO outside of the function and make the constructor take a string as an argument. Then, pass the string from the user to the constructor.

class Person {
public:
    Person(const std::string& name)
      : name_(name) {}
    const std::string& getName() const { return name_; }
private:
    const std::string name_;
};

...

std::string name;
std::cin >> name;
Person person(name);

Upvotes: 5

Related Questions