Array of objects questions.

I am very confused about array of objects coding. I have looked around a bit, and nothing of what I found was helpful in having me actually understand it (cause most of it was just all code and no words).

So I don't know how to work an array of objects for data members. Anything anyone could tell me that can help me understand this would be greatly appreciated.
An array is simply a list of objects stored consecutively. Each object can be accessed by its position in the array.

char arr[] = { 'a', 'b', 'c', 'd' };

This is an array of the first four letters of the English alphabet. You can access 'a' with arr[0], and 'c' with arr[2];

cerr << arr[1] << ' ' << arr[3] << '\n';

Should print:

b d
You should use the std::vector.
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 <cstdlib>
#include <iostream>
#include <vector>

using namespace std;

class cat{
     public:
            int age; 
};

int main()
{
    cat cat1;
    cat cat2;
    vector<cat> catArray;

    catArray.push_back(cat1);
    catArray.push_back(cat2);
    
    catArray[0].age = 3;
    catArray.at(1).age = 6;
    
    cout << catArray.front().age << endl;
    cout << catArray.back().age << endl;
}

Last edited on
To really understand either [] or vector<> well, you need to understand the amount of memory allocated and value semantics (when are copy constructors called?).

For example, you should understand it enough to know why:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Parent {
  public:
    Parent() { }
};

class Child1 : public Parent {
};

class Child2 : public Parent {
};

vector<Parent> this_is_bad;  // cannot hold a mixture of Child1 and Child2
vector<Parent*> this_is_ok;  // holds anything that points to a derivation of Parent, including Parent*
vector<Parent&> this_is_also_bad;  // not allowed - why? 


Just remember, a [] or vector<> just points to a chunk of contiguous memory.
You should be able to draw what this chunk of memory looks like.
Well, this is for making an array of objects from data members of a class.

For example.

1
2
3
4
5
6
class pets
{
string PetName;
Int PetNum;
string Species;
}


I need to make a class in order to make an array of objects through the private data members.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <string>

//All the members of this class are private, and it has no public methods.
// For testing you may want to use a struct instead.
class pets
{
  string PetName;
  int PetNum; //lowercase 'i' in "int"
  string Species;
}; //don't forget the ;

int main() {
  const int N = ...;
  pets inventory[N]; //creates an array of N pets

  ... inventory[0] //do something with the first pets object
  ...

  return 0;
}
Topic archived. No new replies allowed.