Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good practice to initialize a member variable of a class in the header file? [closed]

Tags:

c++

Let's say I have a pointer and I want it to be initialized to nullptr. Which option would be better, to create a constructor that sets that member variable to nullptr or just initialize it in the declaration on the header file to nullptr.

Is there any differences at all? Is the latter considered bad practice?

Thanks in advance.

like image 972
elmarki Avatar asked Dec 31 '22 15:12

elmarki


1 Answers

Initializing a member in the class body is completely equivalent to doing it in the member initializer list in the construcor. (But if you provide initializers in both places, member-init-list overrides initializers in class body.)

Initializing in the class body whenever possible is a good practice, because it's less error prone (you'll immediately notice if you forget to initialize a newly added member; see DRY).

like image 163
HolyBlackCat Avatar answered Jan 28 '23 10:01

HolyBlackCat