I have a class field
char chars[4]
I want to init this field in the constructor.
My constructor need to get char chars[] as a parameter and in the constructor call I want to init my class fields.
Can I do it or I need to call copy?
Use std::copy like this:
class MyClass
{
char m_x[4];
public:
MyClass(const char (&x)[4])
{
std::copy(x, x + 4, m_x);
}
};
You should really be explicit with your types here to enforce that you pass exactly 4 elements.
MyClass(const char x[4]) is the same as MyClass(const char* x).You need to call copy.
MyClass::MyClass(const char* param)
{
std::copy(param, param + 4, chars);
}
This is slightly risky code since there is no guarantee that param has four characters to copy.
char* is exactly the same as char[], and const char * is exactly the same as const char[]. But only for parameters.int* is the same as int[] for instance. The reason is that you cannot pass an array as a parameter in C/C++. So the designers of C chose to use the array syntax to mean the same as a pointer for parameters. If you want to say char[] then do it like that. It won't make any difference.An alternative could be to use a vector<char> which can be initialised in the initialiser list:
class A
{
public:
A(char* a): a_(a, a + strlen(a)) {}
private:
std::vector<char> a_;
};
See demo at http://ideone.com/x9p6I .
This could be made into a template to support different types but would require the number of elements in the array to be provided to the constructor (as strlen() would not be applicable to an array of int). For example:
template <class T>
class A
{
public:
A(const T* a, const size_t count): a_(a, a + count) {}
private:
std::vector<T> a_;
};
See demo at http://ideone.com/hhoaC .
Yes. You need to copy the contents from the input parameter.
std::copy for some reason.
std::string,std::vectororstd::arrayinstead.