user3266738
user3266738

Reputation: 497

Initialization of a C++ Struct with a user defined constructor

I have defined the following struct and its default constructor:

struct State
{
  State()
  {
     // Initialize both stacks with unit matrices
     objStack.push(Matrix(1, 1, 1, SCALE));
     lightStack.push(Matrix(1, 1, 1, SCALE));
  }

  std::stack<Affine> objStack;
  std::stack<Affine> lightStack;

  int maxDepth = 5;
  std::unique_ptr<Point[]> vertices = nullptr;
  Colour ambient = Colour(0.2);
};

If the constructor I declared is executed when I instantiate a State struct, will the last 3 variables still be initialized with 5, nullptr and Colour(0.2)? Or should my constructor look like this:

  State()
  {
     // Initialize both stacks with unit matrices
     objStack.push(Matrix(1, 1, 1, SCALE));
     lightStack.push(Matrix(1, 1, 1, SCALE));

     maxDepth = 5;
     vertices = nullptr;
     ambient = Colour(0.2);
  }

I'm not sure about what will happen here.

Upvotes: 0

Views: 2366

Answers (1)

TrentP
TrentP

Reputation: 4682

In C++11 or later, your first example is correct. It will initialize the class members as part of the construction process and this will happen before the body the struct State constructor is called. Prior to C++11, the in-class initialization of members in that manner is not valid and will not compile. You would instead write the following parts differently, using an initializer list, which produces the same behavior in as your C++11 code.

struct State
{
  State() : maxDepth(5), verticies(NULL), ambient(0.2)
  { ...
  }

  int maxDepth;
  std::unique_ptr<Point[]> vertices;
  Colour ambient;
};

If you write code to set the class members in the body of your constructor, they will be set twice. Once before the struct's constructor executes via the members' default constructors, then again when you set their values in the struct's ctor's body. An int, or other primitive type, doesn't have a default constructor, so it would be uninitialized before the code in the struct ctor body sets it. But an object like the std::unique_ptr would be set twice since it does have a default CTOR that would be used before the struct ctor body runs.

Upvotes: 3

Related Questions