Axel Kennedal
Axel Kennedal

Reputation: 555

Creating an array of objects c++

I'm trying to create an array (c++) that consists of 4 objects and I'm using this syntax, something is obviously wrong, but what?

for (int octet = 0; octet < 4; octet++) {
        cout << "OCTET NO." << octet << endl;
        cout << "IP:     "; cin >> ip;
        cout << "Subnet: "; cin >> subnet;

        networkOctet[octet] = networkOctet(ip, subnet); //The line where the problem is

        }

Thank you for your help!

!-- UPDATE --!

Allright, so I changed the code to this but now it says "no matching constructor for initialization of 'networkOctet[4]'"... I have a constructor that is declared, defined and works perfectly on objects that are not in arrays.

Updated code:

int ip;

int subnet;

networkOctet networkOctetObject[4];

for (int octet = 0; octet < 4; octet++) {
    cout << "OCTET NO." << octet << endl;
    cout << "IP:     "; cin >> ip;
    cout << "Subnet: "; cin >> subnet;
    if (octet == 3) {
        networkOctetObject[octet] = networkOctet(ip, subnet, true);
    }
    else {
        networkOctetObject[octet] = networkOctet(ip, subnet, false);
    }
}

Upvotes: 1

Views: 140

Answers (2)

sleepy1771
sleepy1771

Reputation: 319

You can only create an array of types that do have a default constructor. If you defined your own constructor and did not add a default constructor then you cannot create an array of this type because the compiler tries to value-initializes all elements (using the default constructor) in the array when the array is created. If you drop the default constructor the elements in the array cannot be value-initialized (because there is no default constructor) and your mentioned compiler error appears.

When the compiler sees the line

networkOctet networkOctetObject[4];

it tries to create 4 objects of type networkOctet. To create those objects a constructor of networkOctet must be called. As you create an array the compiler tries to call the default constructor that is not available. This is the line where the error occures. So to make your code work add a default constructor by adding

networkOctet() {
    // Initialize a networkOctet to a valid default value
}

to your networkOctet class (notice that this default constructor must be public).

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258618

I doubt you overloaded both [] and () on a type decltype(networkOctet), so the problem is that you're treating the name as both a variable networkOctet[octet] and a type networkOctet(ip, subnet). If your variable of type X[4] is named y, you'd use the following syntax to make this work:

y[octet] = X(ip, subnet);

where y itself is declared as X y[4].

Upvotes: 1

Related Questions