user3249763 user3249763 - 12 days ago 5
C++ Question

Assigning an array of pointers to a private variable in C++

In my header file, I have the following code

class ExEvent : public Event {
public:
ExEvent(
Item* dst[SIZE],
);
~ExEvent();
Item* dst[SIZE];
};


In the cpp file, I have the following code

ExEvent::ExEvent(
Item * dst[SIZE],
) : Event() {
this->dst = &dst;
}


I get the following error:

error: array type 'Item *[15]' is not assignable
this->dst = &dst;


Can someone explain why this error happens and why I cannot assign dst array pointer to this->dst.

Answer

In function arguments type[any-size] is actually type*. I.e. ExEvent(Item*[SIZE]) is, in fact, ExEvent(Item**).

Hence, to fix the code:

ExEvent::ExEvent(Item* src[SIZE])
{
    std::copy_n(src, SIZE, this->dst);
}

Make sure that src has enough elements.

See declaring functions: parameter list for more details:

If the type is "array of T" or "array of unknown bound of T", it is replaced by the type "pointer to T"

Comments