looping objects?

any reason why I cant do this?
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
#include<iostream>
#include<string>
using namespace std;

class ball{

public:
	int rad=10;
};


int main(){
	string s;
	cout << "Add ball?";
	cin >> s;
	int i=1;
	if (s == "y"){

		new ball b[i];
		i++;
		cout << b[i].rad+i;
	}


}


When I call the instance b[i] its higlights b saying "expected ;"
Line 19 is incorrect. The correct syntax for new is ball* b = new ball[i]; . But this is likely not what you want. If it is, then remember to call delete[] b; when b is no longer needed. e.g:

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
#include<iostream>
#include<string>
using namespace std;

class ball{

public:
	int rad=10;
};


int main(){
	string s;
	cout << "Add ball?";
	cin >> s;
	int i=1;
	if (s == "y"){

		ball* b = new ball[i];
		i++;
		cout << b[i].rad+i;
		delete[] b;
	}


}


However there is an error on line 21 where you are accessing beyond the array of objects.
I will leave you with what I think you wanted, but still with the error on line 21.

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
#include<iostream>
#include<string>
using namespace std;

class ball{

public:
	int rad=10;
};


int main(){
	string s;
	cout << "Add ball?";
	cin >> s;
	int i=1;
	if (s == "y"){

		ball b[1];
		i++;
		cout << b[i].rad+i;
	}


}


Last edited on
Thanks for answering.

Why are you using pointers for the ball?

I want to create as many ball objects with radius r as the user wants and I eventually want to save them to a text file.
i'll point you to http://www.cplusplus.com/doc/tutorial/dynamic/ which should explain how to use dynamic memory a little better.

The reason you use a pointer for ball (b) is new returns a pointer. But in Ball b[1] b is also a pointer, although to static memory. b holds the pointer to the memory, while b[number] dereferences the memory. you could also do *(b+number) to do the same thing. You can read more here http://www.cplusplus.com/doc/tutorial/pointers/
Topic archived. No new replies allowed.