1

So I have a class which has a const string data member.

the string itself in received from the user.

how do I write a constructor that can use it and how do i get the string from the user and put it in the class?

thanks

  • As a general piece of advice, non-assignable data members (such as e.g. `std::string const member;`) can make a class awkward to use. It is very common to leave the members non-const, while ensuring that users of the class can only ever see it through a non-mutable interface, if they need to see it at all. This advice might seem to go against the spirit of const safety, but nonetheless it can spare you a lot of pain. – Luc Danton May 20 '13 at 09:33
  • @LucDanton I think no. It doesn't go against the spirit of const safety. const safety is more on how the classes behaves when it is in a "constant state" or the other. It is more of what constraints are imposed by the class interface on its members and not what the members imposes on the class interface. And so, simply put, your piece of advice is correct. :) – Mark Garcia May 20 '13 at 09:39

1 Answers1

5

To initialize const members (as well as reference members) you need to use constructor initialization lists.

This is how you would do it in C++11 (the string is passed by value and then moved, so that no copying will be performed when an rvalue is given in input to the constructor):

#include <string>

struct X
{
    X(std::string s_) : s(std::move(s_)) { }
//                    ^^^^^^^^^^^^^^^^^^
    std::string const s;
};

In C++03 you would do it this way:

#include <string>

struct X
{
    X(std::string const& s_) : s(s_) { }
//                           ^^^^^^^
    std::string const s;
};
Andy Prowl
  • 124,023
  • 23
  • 387
  • 451