vector class constructors

Oct 26, 2011 at 3:03pm
Yes, this is a homework problem. I need a hint. I think I'm making something more difficult than it is. I'm trying to write a vector library and am having trouble with the default and value constructors.


Here is a cut from the interface file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
  private:

    double Vec[MAX];    // Elements of vector
    unsigned Len;       // Length of vector

  public:

    // Default constructor (N elements, initialize each element to Value)
    //
    Vector( unsigned N = 1, double Value = 0.0 );

    // Value constructor (copy an array of N values)
    //
    Vector( double Array[], unsigned N );



Here is my attempt at defining them in the library:

1
2
3
4
5
6
7
8
9
10
11
Vector::Vector( unsigned N, double Value )
{
  Len = N;
  Vec[Len] = {Value};
}

Vector::Vector( double Array[], unsigned N )
{
  Len = N;
  Vec[Len] = Array[Len];
}


I think my biggest problem is that I don't understand what the difference between a default constructor and value constructor is supposed to be. Is the default constructor just there for when an "Vector();" is constructed?

Thanks for your time.
Oct 26, 2011 at 3:14pm
A default constructor contains no parameters, or if it has parameters, they all have default values.

More details can be found here...

http://www.cplusplus.com/doc/tutorial/classes/

Oct 26, 2011 at 3:20pm
I'm guessing you're trying to assign "Value" to each element of "Vec", but that's not the way to do it.Vec[LEN] assigns a value to the (LEN+1)'th element of Vec (which will cause an access violation error, as there are only LEN spaces available). The {} values works only when calling the constructor.

The bad news is: array constructors only support one "default value fill". The good news is: that default value is 0! As a result, this should work:
int Vec[LEN] = {Value};
The bad news is: this only works during declaration (or maybe it can be called at some other point, but I don't know how). The good news is: there's a function "std::fill_n":
http://stackoverflow.com/questions/1065774/c-c-initialization-of-a-normal-array-with-one-default-value
Topic archived. No new replies allowed.