Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value of a struct member

(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?

like image 628
bakester14 Avatar asked May 22 '16 02:05

bakester14


People also ask

Can struct members have default values?

Default values MAY be defined on struct members. Defaults appear at the end of a field definition with a C-like = {value} pattern.

Are struct members default initialized?

In a structure declared as static, any members that are not initialized are implicitly initialized to zero of the appropriate type; the members of a structure with automatic storage have no default initialization.

How do you give a struct a default value?

Default values can be assigned to a struct by using a constructor function. Rather than creating a structure directly, we can use a constructor to assign custom default values to all or some of its members. Another way of assigning default values to structs is by using tags.

Are struct members initialized to zero?

If a structure variable does not have an initializer, the initial values of the structure members depend on the storage class associated with the structure variable: If a structure variable has static storage, its members are implicitly initialized to zero of the appropriate type.


1 Answers

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.

like image 173
songyuanyao Avatar answered Sep 30 '22 13:09

songyuanyao