Is this code valid in C++?
class MyClass
{
public:
Class2 array [100];
Myclass (const Myclass& other) : array (other.array) {}
};
If it isn't, what's the best way to achieve the same result?
In C++ arrays are not explicitly copyable (not copy-constructible, not assignable). Your code will not compile.
Yet in C++ arrays become indirectly copyable when wrapped into a class. This means that if you remove your constructor definition, then the implicit copy constructor generated by the compiler for your class MyClass
will actually successfully copy the array by some "magical" means that are not available to you directly.
But if for some reason you have to define the copy constructor explicitly, then your options are restricted to leaving the array default-initialized and then explicitly copying the data in the body of the constructor through std::copy
or something similar. Or you can simply re-wrap your array, which is actually what the already suggested std::array
can do for you.
Regardless of whether or not this is valid, if all your copy constructor does is to copy the array, then I would rather avoid writing it and let the compiler generate one implicitly.
Also, I would recommend following chris's advice in C++11 and use std::array
rather than C-style arrays:
#include <array>
class MyClass
{
public: // In case you really want this to be public
std::array<Class2, 100> arr;
};
By the way, this would also allow you to initialize you array in the copy constructor's initializer list (but again, do this only if needed):
class MyClass
{
public:
MyClass() { }
MyClass (const MyClass& other) : arr(other.arr) {}
// ^^^^^^^^^^^^^^
private:
std::array<Class2, 100> arr;
};
Here is a live example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With