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
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
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;
};