According to C ++ standard (9.2 Class members)
9 Non-static (9.4) data members are not incomplete types.
This arr data member declaration
int arr[];
is incomplete because the size of the array is unknown. And besides, the array declaration cannot contain a zero size. Therefore, the definition of your class itself is incorrect.
You should either dynamically create an array yourself, depending on the size of its size, or use the ready-made class std::vector<int> .
If for educational purposes you need to work with the dynamic distribution of arrays, then the class declaration might look like this (I did not include the movement constructor and the movement operator)
#include <iostream> #include <algorithm> #include <utility> #include <cstdlib> #include <ctime> class Demo { private: size_t size = 0; int *arr = nullptr; public: typedef size_t size_type; typedef int value_type; Demo() = default; Demo( size_t i ) : size( i ), arr( i == 0 ? nullptr : new int[i] ) { if ( arr ) { std::generate( arr, arr + size, [] { return std::rand() % 10; } ); } } Demo( const Demo &rhs ) : size( rhs.size ), arr( rhs.size == 0 ? nullptr : new int[rhs.size] ) { if ( arr ) { std::copy( rhs.arr, rhs.arr + rhs.size, arr ); } } ~Demo() { delete []arr; } Demo & operator =( const Demo &rhs ) { Demo tmp( rhs ); swap( tmp ); return *this; } void show() const { for ( size_t i = 0; i < size; ++i ) std::cout << arr[i] << ' '; std::cout << std::endl; } void swap( Demo &rhs ) { std::swap( size, rhs.size ); std::swap( arr, rhs.arr ); } size_type get_size() const { return size; } }; void swap( Demo &lhs, Demo &rhs ) { lhs.swap( rhs ); } int main() { std::srand( ( unsigned int )std::time( 0 ) ); Demo a1( 5 ); Demo a2( 10 ); a1.show(); a2.show(); swap( a1, a2 ); a1.show(); a2.show(); }
The program may have the following output to the console:
1 8 5 1 2 7 3 1 4 2 9 2 9 9 4 7 3 1 4 2 9 2 9 9 4 1 8 5 1 2
As for the motion constructor and the motion assignment operator, they may look as follows
Demo( Demo &&rhs ) : Demo() { swap( rhs ); } Demo & operator =( Demo &&rhs ) { swap( rhs ); return *this; }