Problem involving friend functions and pointers

So in this program I'm supposed to create a class that behaves like a vector with elements containing datatypes of the type "double". I'm not that far in but I'm having problems. I'm trying to write a function that displays the content of the "vector" (not really a vector but a class that's supposed to behave like a vector) and I can't seem to get that function to work.

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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cctype>

using namespace std;

class VectorDouble
{
public:
	VectorDouble(short count = 0, short max_count = 50);
	friend void disp(const VectorDouble& vector);

	
private:
	double* pointer;
	short max_count;
	short count;
};

int main()
{
	char loop = 'y';

	do
	{
		VectorDouble v1(5), v2;

		do
		{
			cout << "Add element\n"
				 << "Display elements\n"
				 << "Check for equality\n";

			//TESTING
			char next;
			cin >> next;
			disp(v1);
		}while(true);//ADD CONDITIONS

		cout << "Would you like to run the program again? (y/n)? ";
		cin >> loop;
		loop = tolower(loop);
		while(loop != 'y' && loop != 'n')
		{
			cout << "Incorrect output. Would you like to run the program again? ";
			cin >> loop;
		}
	}while(loop == 'y');

	cout << "Press a key to exit: ";
	char exit;
	cin >> exit;

	return 0;
}

VectorDouble::VectorDouble(short count, short max_count): count(count), max_count(max_count)
{
	//default constructor
}

void disp(const VectorDouble& vector)
{
	for(short i = 0; i < vector.count; i++)
	{
		cout << vector.pointer[i] << " ";
	}
}


The function is on line 63 and I'm guessing line 67 is giving me trouble. I get a runtime error saying something along the lines of " unhandled exception... Access violation reading location..." Anyway even if this code would work I still don't think it would produce the right result because I want line 67 to display the value of the variable being pointed to, not the address. To try to mediate this problem I tried to do the following:

cout << *vector.pointer[i] << " ";

and

cout << vector.*pointer[i] << " ";

Note the "*" where there was none before. When I try the above solutions then my code doesn't even compile. Please help.
vector.pointer[i] behaves like you expect and will produce a double (assuming pointer points to a block of memory containing at least i + 1 doubles).

Your issue is that pointer is uninitialized. In the constructor, you need to do something like
pointer = new double[count];. Remember to delete [] it when necessary and to provide a destructor and copy constructor.
Thanks shacktar, I got it working.
Topic archived. No new replies allowed.