Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bad array initialization vs assignment copy constructor initialization

#include<iostream>
using namespace std;

class Test
{
public:
    Test(){}
    Test(int param):i(param){}
    int i;
};

int main()
{

    Test obj1(100);
    //Test obj2[100](obj1) ;  - This doesn't work I know
    Test obj3[10] = obj1; //This works
    cout<<obj3[9].i<<endl;
    return 1;
}

In the above code Test obj2[100](obj1); doesn't work but Test obj3[10] = obj1;

Why is the former supported but latter.(Both would be calling the copy constructor.)

Is that the former isn't supported because of implementation constrains in compilers?

Edit: I am not using c++11. gcc version 4.8.2 (i686-posix-dwarf-rev3, Built by MinGW-W64 project) Qt 5.3.1

Any conclusion?

like image 543
InQusitive Avatar asked Nov 09 '22 20:11

InQusitive


1 Answers

I'm mainly answering your last comment, because all elements were already given in comments.

What can we see :

  • first syntax Test obj2[100](obj1); is rejected as error by all compilers tested because ... it does not follows specification for C++ language !
  • second syntax Test obj2[100] = obj1; does not seem to cleanly fit to current specifications because you initialize an array with a single element. More on that :
    • clang (and MSVC) will clash on it : they require curly braces and then initialize only first element (would be : Test obj2[100] = {obj1};)
    • gcc (4.5 to 4.9) accepts it and initializes all elements of array with a copy of obj1

My opinion is that as it unclear that it is correct C++ and as it causes errors on some heavily used C++ compilers, you should avoid to use even the second syntax, unless documenting that in red flashing font.

like image 156
Serge Ballesta Avatar answered Nov 14 '22 22:11

Serge Ballesta