Issue
Considering this program:
#include <iostream>
class C
{
public:
C(void): a(1)
{ a=2; }
int a{3};
};
int main(void)
{
C c{};
std::cout << c.a; // 2
}
I can see three forms of data member initialization:
- using a member initializer list
- using the Constructor
- using a declaration in the class body
When to use which?
Solution
1: Using a declaration in the class body
You should use this when the member will always be initialized with the same value, and it doesn't make sense to have to explicitly write that for each constructor.
2: Using a member initializer list
The member initializer list is obviously necessary for a member that lacks a default constructor, but aside from that, if you're initializing a member based on the constructor, it makes sense to do it here.
3: Using the constructor body
The constructor body is more useful for logic that can't be performed in a single statement (in the init-list). However, I don't think there is much difference between initializing a POD in the member initializer list or the constructor body.
Answered By - Weak to Enuma Elish Answer Checked By - Candace Johnson (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.