Search code examples
c++default-constructorconstruct

Why parameterized constructor can't be called while creating array of class Objects?


I am new to C++, I need some clarification about the constructor and my question here is:

  1. Can we use a parameterized constructor while creating an array of class objects?
  2. Or is it only possible to use a default constructor when creating an array of class objects?

Please explain how it can be done, or why it can't. I need a deeper understanding about this.


Solution

  • You can use a parameterized constructor to initialize an array. See the following example.

    class Foo
    {
    public:
        Foo(int _a, bool _b) : a{_a}, b{_b} {}
    private:
        int a;
        bool b;
    };
    
    int main() {
        Foo things[] = {{5, true},
                        {3, false},
                        {7, true}};
        return 0;
    }
    

    The array things is of Foo objects. I am using uniform initialization to construct 3 Foo objects in the array. These are relying on the parameterized constructor that I defined in the class.