basic c++ Declaration of an array of objects inside another class

Hello!
i've been working on a code and I tried to declare an array of objects inside the private of another class,
I have a class called Contacts which goes like this,
1
2
3
4
5
6
7
8
9
10
11
12
class Contacts
{
 private:
 char Name[50], Num[10];
 public:
 void InputContact()
 {
 }
 void OutputContact()
 {
 }
};

And I have another class called Addressbook which goes like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
class Addressbook
{
 private:
 static n;
 Contacts rec[n=1];
 public:
 void AddContact()
 {
 }
 void DisplayContact()
 {
 }
};

But when I compile this code I get the following error:

D:\C++ Project\test.cpp|49|error: data member may not have variably modified type `Contact[(((unsigned int)((AddressBook::n <unknown operator> 1), 0)) + 1u)]'|

How do I declare an array of objects inside another class?
Last edited on
I'm sorry, but that didn't help can someone please tell me how to declare/initialize an array of objects of a class inside another class?
Shashank Setty wrote:
I'm sorry, but that didn't help can someone please tell me how to declare/initialize an array of objects of a class inside another class?
That's not your problem. On line 4/5 of Addressbook you try to declare a dynamic array. This is not how it works. Use vector instead:

http://www.cplusplus.com/reference/vector/vector/?kw=vector
closed account (48T7M4Gy)
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
47
48
49
50
51
52
53
class Contact
{
private:
    char* name;
    char* number;
    
public:
    
    Contact()
    {
    }
    
    Contact(char* nme, char* num)
    {
        name = nme;
        number = num;
    }
    
};

class AddressBook
{
private:
    Contact* contacts;

public:
    AddressBook(Contact* cs)
    {
        contacts = cs;
    }
    
    void addContact( Contact* c)
    {
        contacts = c;
    }
};

int main()
{
    const int limit = 50;
    Contact *contacts = new Contact[limit];
    
    AddressBook addbook = AddressBook(contacts);
    
    char name[50] = "Bob";
    char num[10] = "2143";
    
    contacts[1] = Contact(name, num);
    
    addbook.addContact(&contacts[1]);
    
    return 0;
}


This needs to be refined a bit and there are a couple of bloopers but the essence is there. The 'essence' here means you don't create the actual array in the addressbook but refer to it by pointers. It becomes cumbersome to keep track of entries so, vectors aren't a bad move unless you want the challenge. You could also do it with a linked list of your own design.
Last edited on
Thank you so much @coder777 and @kemort I fixed it :)
Topic archived. No new replies allowed.