Avihai Marchiano
Avihai Marchiano

Reputation: 3927

How to set array in c++

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?

Upvotes: 0

Views: 244

Answers (5)

PermanentGuest
PermanentGuest

Reputation: 5331

Yes. You need to copy the contents from the input parameter.

Upvotes: -2

tenfour
tenfour

Reputation: 36896

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.

Upvotes: 5

hmjd
hmjd

Reputation: 121971

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 .

Upvotes: 2

Vitaly Davydov
Vitaly Davydov

Reputation: 61

As I understood, you need to create Conversion constructors, it should looks like this: A::A(const char* string) {strncpy(chars, string, 4); }

Upvotes: -1

john
john

Reputation: 8027

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.

Upvotes: 3

Related Questions