pointer/array of classes.

Hi guys. I am trying to explore all the different ways to use pointer with classes. However I am stuck with the following thing.

1. Calling an array in the class with pointer.
2. Creating more memory/items of classes. The "New" command.

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
#include <iostream>
#include <string>
#include <fstream>
using namespace std; 
const int ARRAYSIZE = 2; 

class TypeOfAnimal{
public:
	int bob;
	string bob2; 
	int animalAge(){
	return(3); 
	}
	string animalName(){
		return("Dog");
	}
	string animalType(int & input){
		if(input == 1)
			return("mammal"); 
	}

	int animalLegs[5];
	
}*P_Animal[ARRAYSIZE], Animal[ARRAYSIZE];

 int main(){
	int input(1); 
	 
	 //normal class/array call & assigning value. 
	Animal[0].bob = 3;
                cout << Animal[0].bob << endl; 
	
	//normal class/array call with pointer call.
	for(int i = 0; i <= ARRAYSIZE; i++){
		cout << P_Animal[i] -> animalAge() << endl; 
		cout << P_Animal[i] -> animalName() << endl;
	}
 
	//test assigning values with pointer. 
	cout << P_Animal[0] -> animalType(input); 
	
	//test calling array within class withpointer. <-- stuck here. 
	P_Animal[0] -> animalLegs[0] = 4; 
	P_Animal -> new TypeOfAnimal[5]; 
	
}


And the complier error message doesn't help either. All it said is "error before the new"...etc. Some help and demonstration would greatly be appreciated. Thx guys.
Last edited on
It says that it has a problem with the new:
syntax error : 'new'
P_Animal is an array of pointers to TypeOfAnimal.
To create a new object from a pointer in the P_Animal class you should use:
P_Animal[position] = new TypeOfAnimal
You can only use the -> operator with pointers. Not with arrays. So the P_Animal -> new TypeOfAnimal[5]; is illegal

[EDIT] Also because P_Animal is an array of pointers you can not use P_Animal[0] -> animalLegs[0] = 4; before creating an object of type TypeOfAnimal for this pointer or referencing this pointer to an object.

Hope this helps
Last edited on
Topic archived. No new replies allowed.