Copy Constructor

I'm working on a program for a dynamic array. The programs compiles however it crashes when I try to use the copy constructor the program crashes.

VectorN.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#ifndef VECTORN_H
#define VECTORN_H

#include <iostream>

using namespace std;

class VectorN
	{
	private:
		float *vArray;
		int vSize;
	public:
		VectorN();
		VectorN(float vector[], int newSize);
		float& operator[](int i);
		float operator[](int i) const;
	
	friend ostream& operator<<(ostream &leftOp, const VectorN& rightOp);
	};

#endif 


VectorN.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include "VectorN.h"
#include <iostream>
#include <iomanip>
#include <fstream>

VectorN::VectorN()
	{
	vArray = new float[vSize];
	vSize = 0;
	}
	
VectorN::VectorN(float vector[], int newSize)	
	{
	vSize = newSize;
	if (vSize > 0)
		{
		for (int i = 0; i < newSize; i++)
			{
			vArray[i] = vector[i];
			}
		}
	else
		{
		vArray = NULL;
		}	 	 
	}

ostream &operator<<(ostream &leftOp, const VectorN& rightOp)
	{
	leftOp << "(";
	for (int i = 0; i < rightOp.vSize; i++)
		{
		leftOp << rightOp.vArray[i] << ", ";
		leftOp << rightOp.vArray[i];
                }
	leftOp << ")";
	return leftOp;
	}
	  
float& VectorN::operator[](int i)
	{
	return vArray[i];
	{
	
float VectorN:: operator[](int i) const
	{
	return vArray[i];
	{	 


Driver Program
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <stdexcept>
#include "VectorN.h"

using std::cout;
using std::endl;
using std::out_of_range;

int main()
   {
   int test = 1;

   cout << "\nTest " << test++ << ": Default constructor and printing\n" << endl;

   const VectorN v1;

   cout << "v1: " << v1 << endl;
   
   cout << "\nTest " << test++ << ": Array constructor and printing\n" << endl;
   
   float ar2[] = {1.0, 2.0, 3.0};

   const VectorN v2(ar2, 3);

   cout << "v2: " << v2 << endl;   

   return 0;
   }  
Last edited on
In the VectorN(float[], int) constructor you forgot to create the array that vArray should point to.
Thank you very much. That fixed the problem.
Topic archived. No new replies allowed.