Help using classes

I have a class that uses another class type and I can't figure out how to access it.

This is just a simplified example but I think it's enough to explain my problem.

If I have a class First and class Second:

1
2
3
4
5
6
7
8
9
10
11
12
Class First
{
public:
   int apples;
   int bananas;
}

Class Second
{
public:
   First fruits[10];
}


and then I say: Second someObject;

how do I decalre apples and bananas from this Second class type object? My best guess is someObject.fruits[someInt].apples (but that isn't working)



Last edited on
fruits[i].apples = 10 //for example.

At the i-th object the number of apples will be = 10 and if your classes contains no member functions just only variables use structs.
Thanks for the reply.

but in your example you don't refer to the Second class type object... so how could that work?
Apples and bananas for the objects can be declared using the following method add this to the public section of your class.

1
2
3
4
5
6
7
8
9
10
11
void addApplesBananas()
{
	for(int i=0;i<9;i++)
	{
		fruits[i].apples = 10;
		fruits[i].bananas = 100;
	}
}

//That will make each object fruits in the array has the number of apples = 10 and number
//Of bananas = 100. 
closed account (D80DSL3A)
I had to correct some syntax errors but the following is working:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class First   // not Class
{
public:
   int apples;
   int bananas;
};        // semi-colon goes here

class Second
{
public:
   First fruits[10];
};

int main()
{
	Second s;
	s.fruits[0].apples = 3;
	s.fruits[0].bananas = 4;
        return 0;
}
This maybe more usefull
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
#include <iostream>
using namespace std;

class First
{
public:
   int apples;
   int bananas;
};

class Second
{
public:
   First fruits[10];
   void addApplesBananas()
   {
   	for(int i=0;i<10;i++)
   	{
   		fruits[i].apples = 10;
   		fruits[i].bananas = 100;
   	}
   }
};


int main()
{
	Second x;
	x.addApplesBananas();
	for(int i=0;i<10;i++)
	{
		cout << "Apples in " << i+1 << " th element = " << x.fruits[i].apples << endl;
		cout << "Bananas in " << i+1 << " th element = " << x.fruits[i].bananas << endl << endl << endl;
	}
}


Outputs:
Apples in 1 th element = 10
Bananas in 1 th element = 100


Apples in 2 th element = 10
Bananas in 2 th element = 100


Apples in 3 th element = 10
Bananas in 3 th element = 100


Apples in 4 th element = 10
Bananas in 4 th element = 100


Apples in 5 th element = 10
Bananas in 5 th element = 100


Apples in 6 th element = 10
Bananas in 6 th element = 100


Apples in 7 th element = 10
Bananas in 7 th element = 100


Apples in 8 th element = 10
Bananas in 8 th element = 100


Apples in 9 th element = 10
Bananas in 9 th element = 100


Apples in 10 th element = 10
Bananas in 10 th element = 100
Thanks guys, just what I needed. I got the program working.
Topic archived. No new replies allowed.