How an object array works for initialization

Asked 2 years ago, Updated 2 years ago, 26 views

#include <iostream>
using namespace std;

class Test
{
    private:
        int num;
    public:
        Test(int n) : num(n)
        {
            cout << "Constructor : " << n << endl;
        }
        Test(const Test& copy) : num(copy.num)
        {
            cout << "Copy constructor : " << copy.num << endl;
        }
};

int main(void)
{
    Test pArray[2] = {Test(1),Test(2)};

    return 0;
}

I was curious about the initialization method, so after testing it, they called the constructor. When you initialize a new object using an existing object, you call the copy constructor.

Therefore, if the individual index objects of the pArray array are matched to Test(1)~~ and initialized there, I think you should call the copy constructor. But by calling the constructor, it's not the case, is it?

In other cases, pArray[0] and pArray[1] are pre-generated pArray[0] = Test(1); pArray[1] = Test(2); If so, I thought that a total of 4 times should be called, 2 times for the constructor of individual pArray[0], 2 times for Test(1), and 2 times for Test(2).

And since it's not initializing the object, it's putting it in place, so the substitution operator has to be called, but it doesn't get called when I implemented the substitution operator for confirmation.

I wonder how it works

c++

2022-09-22 21:52

1 Answers

Grammatically, array initialization is an independent grammar in itself.

Test pArray[2] = {Test(1),Test(2)};

Wow, the following is a completely different concept.

pArray[0] = Test(1);
pArray[1] = Test(2);

If examples do not use initialization statements.

Test pArray[2];

The above is actually the same meaning as the following.

Test pArray[2] = {Test(),Test()}

The reason is that the pArray array consists of Test objects. In other words, to complete an array, elements of the array must also be created. This is also true for normal types. The same is true for normal types.

int iArray[2]; 
// Equivalent to
int iArray[2] = {0,0}; // int is equivalent because the default value is 0. (Depending on the compiler optimization, it may not be initialized to zero.)

If the Test class does not have a default constructor, it does not have a default value. This means that you don't know which constructor to call, so grammatically, you have to specify the constructor in all initialization sentences.


2022-09-22 21:52

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.