5

Suppose I have a C++ class set up as follows:

class Foo{
  public:
    struct Pair{
      int x;
      int y;
      Pair(){ x = 2; y = 4; }
    };

  private:
    Pair pairArr[16];
}

Without otherwise initializing the pairArr, what is the default value of the Pair structs inside it? Does C++ call the constructor (initializing it with x=2, y=4) or are the objects not created yet, leaving me with an array of "junk" objects until I initialize the indices myself?

I know if it is an array of a primitive data type, they are default initialized (if I had an array of ints, they would all be 0). However, I don't know if this behavior holds for more complex objects like my struct here.

4
  • You really should learn to use the initializer list in your constructors. Here it makes no big difference, but it can have a real performance implication compared to using the ctor body (depending on the member types). Commented May 11, 2017 at 20:45
  • 3
    "I know if it is an array of an atomic type, they are default initialized" - you know wrong - where are you learning this stuff from? Also, where did you pick up the notion of "atomic type"? Commented May 11, 2017 at 20:47
  • The objects of your array will be default initialized. Since your class is not an aggregate type (because of a user-defined constructor), your default constructor will be called to construct each of the element in the array Commented May 11, 2017 at 20:50
  • 1
    @JesperJuhl That, and member references (as well as any type that's non-copyable and non-moveable) can only be initialized using the initializer list, so in some cases it's not even about performance -- it's the only option at all! Commented May 11, 2017 at 20:59

1 Answer 1

7

Classes and structs are equivalent in , it's only the default access specifier that differs. So check Arrays and Classes, which says:

The normal array declaration style uses the default constructor for each object in the array (if the class has a default constructor)


From a practical point of view, do this in your struct:

Pair() : x(2), y(4) { std::cout << "Called\n"; }

and you will see the message being printed 16 times.

That's a usual approach (to add print messages to constructor to destructor) when you want to know what is called (and usually their order).


Tip: Use an initializer list, rather than assigning values inside the body of the constructor.

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

1 Comment

You should recommend using member initialization instead of assignment in ctor body.

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.