Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the constructor called immediately for an array of objects as a member of the class?

class gene{
    int ind;

    gene() {
        ind = 0;
    }
}

class network {
    gene g[10];
}

main() {
    network n;
}

Should I call the constuctor for each object in the g array, or it will be called automatically?

e.g, should I change the network class as follows:

class network {
    gene g[10];

    network() {
        for(int i = 0; i < 10; i++)
            g[i] = gene();
    }
}
like image 802
Pegah Avatar asked Nov 22 '11 21:11

Pegah


People also ask

What is a constructor a class automatically called?

A constructor in C++ is a special method that is automatically called when an object of a class is created.

Can a constructor be an array?

Arrays can be created using a constructor with a single number parameter. An array with its length property set to that number and the array elements are empty slots.

Which constructor is called automatically when we create an object?

Constructors in C++ Constructor in C++ is a special method that is invoked automatically at the time of object creation. It is used to initialize the data members of new objects generally.

Is constructor a class member?

Constructor is a special non-static member function of a class that is used to initialize objects of its class type. In the definition of a constructor of a class, member initializer list specifies the initializers for direct and virtual bases and non-static data members.


1 Answers

In your case, because gene has a non-trivial default constructor, each element of the array will be default-constructed for you. I.e., no, your change is unnecessary.

In the circumstance that your array's underlying type is a POD type, you will need to initialize the elements manually. However, the way you're doing it is not ideal; you would want to use value-initialization instead:

class network {
    somePodType x[10];
public:
    network() : x() { }
};
like image 160
ildjarn Avatar answered Oct 01 '22 15:10

ildjarn