Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 798
nagarajan Avatar asked Sep 01 '26 13:09

nagarajan


1 Answers

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.

like image 74
Cory Kramer Avatar answered Sep 05 '26 18:09

Cory Kramer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!