Array of Pointers to Class

Can someone help with this question? I'm getting confused to check the null value
A cowshed with 50 boxes as a class variable, each box can be occupied by one cow. Use an array of 50 pointers on cow; if a box is not occupied, the pointer is set to the value NULL

1
2
3
4
5
static int arr[50];
Cow *arr[50] ;
if (arr == 0) {
    return NULL;
}
An array foo of N elements of something.
How does one look at the k-th element of that array?
By dereferencing: foo[k]

1
2
3
4
5
6
Cow* boxes[50] {};

Cow* getCow( size_t k )
{
  return boxes[k];
}

The caller either gets a cow or nullptr.


However, who own's the cows? Who gives them birth? Who is responsible to butcher them before they run out to the wild?

What if you had std::map<size_t,Cow> boxes; ?
You can check whether those boxes have key k,
and you don't have to worry about the delete.
Thank you very much!
I have one more question. I separated my Programm in cpp, hpp, and main. I have created a milking() function. Now i want to implement it in my main function. I also want to create 3 Cow Objects and for each of them to show how much milk we have. This is what i got so far.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 

int main(int argc, char* argv[]) {  
	
// Create 3 Cow Objects 
	
	boxes[0] = new Cow();
	boxes[1] = new Cow();
	boxes[2] = new Cow();


// Milking the cows; they give 5, 6 and 7 liters of milk

	int i = 5;
	int x = 6;
	int z = 7;
	cout << milking(i) << endl;
	return i;
	
}


Last edited on
Topic archived. No new replies allowed.