0
class Base
    {
    public:
        int i;
        Base(int j):i(j){}
    };

    int main()
    {
        Base B(10);
        Base C[10](B);//throws error saying bad array initializer
    }

When I tried to compile this code, above mentioned error was thrown.

Why doesn't C++ compile this code?

Why can't each object call it's default copy constructor and use the member value of B?

Am I missing something in the C++ standard?

4
  • 1
    You can do that with a vector: std::vector<Base> v(10, Base(10)); Commented Dec 5, 2014 at 14:18
  • You could use an initializer list, but that would not have behavior you want Commented Dec 5, 2014 at 14:22
  • @leemes Oops, yes I did mean that. Fixed it Commented Dec 5, 2014 at 14:22
  • I think the closest you can get with arrays might be: Base C[10]{B, B, B, B, B, B, B, B, B, B}; Maybe you can write a macro to generate the code for correct number of copies... Commented Dec 5, 2014 at 14:24

3 Answers 3

2
Base C[10](B);

This is wrong syntax in C++; You cannot initialize array of plain objects by passing arguments.

Sign up to request clarification or add additional context in comments.

Comments

0
Base C[10];

would not work either. You also need to declare an default constructor as you specified one taking an int as an input so the default one is not being generated.

Comments

0

As for me I do not see any reason why this construction

Base C[10](B);

Or for example the following

Base *C = new Base[10]( 8 );

could not be valid. It depends only on how you would like to define the semantic.

However historically for initialization of aggregates in C++ there is used the brace-init list.

So you can write

Base C[10]{ B, 8, 8, 8, 8, 8, 8, 8, 8, 8 };

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.