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();
}
}
A constructor in C++ is a special method that is automatically called when an object of a class is created.
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.
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.
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.
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() { }
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With