Reputation: 12662
Are the following constructors allowed in the same IntList
class?
IntList(int length);
IntList(int data[]);
Upvotes: 1
Views: 118
Reputation: 503913
That's fine, but note that latter is the same as int* data
, which is a pointer and not an array.
Arrays are non-copyable and must be passed by reference:
typedef int array_type[5];
IntList(const array_type& arr); // same as: IntList(const int (&arr)[5]);
You can also take an array of any size using templates:
template <std::size_t N>
IntList(const int (&arr)[N]); // N is the number of elements
But your approach is ultimately unorthodox. If you want to initialize with a range of data, use iterators:
template <typename InputIterator>
IntList(InputIterator begin, InputIterator end);
Now you can iterate from begin
to end
, which can be iterators from any kind of container, like arrays, std::vector
's, std::map
's and more.
But you should be using std::vector<int>
instead of IntList
anyway.
Upvotes: 4
Reputation: 34625
IntList(int length);
IntList(int data[]);
How ever, this not allowed to have as another method.
IntList(int* data); // Error: This is equivalent to IntList(int data[])
// Because an array decays to a pointer.
Both the arguments are different. length
is of type int
and data
is of type int[]
, and is an example of constructor overloading.
Upon your comment as to how use it - This should serve as an example
class IntList
{
int member[5] ; // Added
public:
IntList(int length) ;
IntList( int data[] ) // Should make sure that the passed array size is 5
// or take another argument mentioning the size of
// array being passed.
{
for(int i=0; i<5; ++i)
member[i] = data[i] ;
}
} ;
int a[] = { 1,2,3,4,5 }; // Making sure that array size is 5
IntList obj(a) ; // Array decays to a pointer pointing to first index of the array
Upvotes: 0