5

(I'm sure this question has already been answered, I'm just not sure on the right words to use to ask it. If someone would tell me what the correct terminology is that would be awesome!)

I'm implementing a HashSet in C++ for a data structures class, and I have a question about C++ syntax regarding structs. Here is my code:

struct HashNode
{
    T value;
    HashNode* next = nullptr;
};

Will this code correctly initialize the next pointer to nullptr when new HashNode is called? If not, what is the value of next after new HashNode?

7
  • What about stackoverflow.com/questions/16782103/…? See second answer. Commented May 22, 2016 at 2:31
  • Does it compile? NB These are initial values, not 'default' values. Commented May 22, 2016 at 2:35
  • That's what I was looking for, thank you so much @pingul Commented May 22, 2016 at 2:35
  • @EJP Yes it does, at least on my machine (C++11 I believe) Commented May 22, 2016 at 2:36
  • So you're asking whether the compiler produces correct object code for this construction? Commented May 22, 2016 at 2:37

1 Answer 1

7

Will this code correctly initialize the next pointer to nullptr when new HashNode is called?

Yes, it will be initialized to nullptr. This is in-class brace-or-equal initializer (default member initializer) (since C++11), it will be used if the member is omitted in member initializer list.

Through a default member initializer, which is simply a brace or equals initializer included in the member declaration, which is used if the member is omitted in the member initializer list

If a member has a default member initializer and also appears in the member initialization list in a constructor, the default member initializer is ignored.

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

1 Comment

Thanks for the terminology!

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.