2

From previous post, I learnt that for there are two ways, at least, to declare an array without default constructors. Like this

class Foo{
  public:
  Foo(int i) {}     
};
   Foo f[5] = {1,2,3,4,5};
   Foo f[5] = {Foo(1), Foo(2), Foo(3), Foo(4), Foo(5)}; 

I also learnt that the first one will construct the object using the parameter directly and the second copy constructor is used here. However, when I test the code below. I make the copy constructor private. I expect to see the difference of the copy constructor usage. But it is not what I expected. Neither of the two declarations is working.

class Foo{
  public:
  Foo(int i) {}     
  private:
  Foo(const Foo& f) {}
};
int main(){

   Foo f[5] = {1,2,3,4,5};
   Foo f[5] = {Foo(1), Foo(2), Foo(3), Foo(4), Foo(5)};      
}

Can anybody explain to me why does this happen?

1
  • 1
    @skydoor: Now you have asked exactly 100 questions :-) Commented Mar 6, 2010 at 16:33

1 Answer 1

5

The first won't construct the objects directly. It will first construct a temporary Foo, and then copy the Foo into the element. It's similar to your second way. The difference is that your second way won't work with a explicit copy constructor, while your first will. And conversely, the first will not work with a explicit constructor taking int, while the second will. Stated another way, the first constructor used in the initialization of an element must not be explicit.

Notice that neither way needs to copy. But they still need to check whether the copy constructors are accessible. So, they shall behave as-if they would copy, but they don't really need to do the copy.

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

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.