Tyler Crompton
Tyler Crompton

Reputation: 12662

Can I have an array of integers for one constructor and a single integer for the other constructor?

Are the following constructors allowed in the same IntList class?

IntList(int length);
IntList(int data[]);

Upvotes: 1

Views: 118

Answers (3)

GManNickG
GManNickG

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

Mahesh
Mahesh

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

Erik
Erik

Reputation: 91270

Yes, they're different types so this is valid.

Upvotes: 1

Related Questions